Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

353
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda