Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

351
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda