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

129
Vistas
React app not re-rendering after infinite scroll implementation

Hi guys hoping someone can help me with an issue. I built a function that fetches user posts from backend and returns them as a response:

const [posts, setPosts] = useState([]);

const newsFeed = async () => {
await axios
  .post(`${process.env.REACT_APP_API}/news-feed`)
  .then((res) => {
    setPosts(res.data);
  })
  .catch((err) => {
    console.log(err);
  });
};

This function gets called by useEffect and also whenever a post is submitted, liked, commented on etc. so that users' posts are always re-rendered every time they are modified or added.

It was working fine until I decided to implement Infinite Scroll to my application. I installed the npm package react-infinite-scroll-component and modified my function to look like this:

const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);

const newsFeed = async () => {
await axios
  .post(
    `${process.env.REACT_APP_API}/news-feed/${page}`)
  .then((res) => {
    let newPosts = posts;
    newPosts = newPosts.concat(res.data);
    setPosts(newPosts);
    setPage(page + 1);
  })
  .catch((err) => {
    console.log(err);
  });
};

The infinite scroll is working just fine but now the posts are not being re-rendered every time this function gets called and instead I need to refresh the page to see changes. I tried resetting the state of page back to 1 again on my postSubmit/likeHandler functions but this didn't have any effect. I'm not seeing any errors in the console so am unsure what is going on.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Replace let newPosts = posts; with let newPosts = [...posts]; Passing the same array reference to setState will not cause an update, since the value hasn't changed. By using [...posts], you are creating a new array, causing the component to update.

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