Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

352
Views
Nextjs: avoid infinite loop when adding a conditional render

I have a Next.js application with the following page:

import { useState, useEffect } from 'react';
import axios from 'axios';
import { withRouter } from 'next/router';

import NotFound from '@/pages';
import { Page, PostBlock } from '@/components';

const Main = ({ router }) => {
  const [postsData, setPostsData] = useState({ posts: [], page: 0, pages: 0 });

  function fetchData() {
    axios
      .get('/api/articles', {
        params: {
          page: router.query?.page,
          lang: router.locale,
          tag: router.query.tag,
        },
      })
      .then(response => {
        setPostsData(response.data);
      })
      .catch(error => console.log(error));
  }

  useEffect(() => {
    fetchData();
  }, []);

  // if (!postsData.posts.length) return <NotFound />;

  return (
    <Page title='Home' className='home-template'>
      <div id='grid' className='post-grid'>
        {postsData.posts?.map(post => {
          return (
            <PostBlock
              featured={post.featured}
              key={post.key}
            />
          );
        })}
      </div>
    </Page>
  );
};

export default withRouter(Main);

The api fetches some articles on component mount, and display them in the UI. So far so good.

I also want to display a component in case there are no articles to display or if the api fails, but if I uncomment the line

if (!postsData.posts.length) return <NotFound />;

the application ends up in an infinite loop.

How can I fix this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try setting posts as empty array in case if the data is empty

if (!(postsData.posts||[]).length) return <NotFound />;
about 4 years ago · Juan Pablo Isaza Report

0

You just need to conditional render your loop part like below:

 return (
    <Page title='Home' className='home-template'>
      <div id='grid' className='post-grid'>
        {
          (postsData?.posts||[]).length ?  
            <>
              {postsData.posts.map(post => {
                 return (
                    <PostBlock
                     featured={post.featured}
                     key={post.key}
                    />
                  );
                })
              }
            </> : <NotFound />
         }            
      </div>
    </Page>
  );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!