mercredi 20 janvier 2021

When limit changed, the component is re-rendering and send me back on top

React developers! I have an issue. :)

So when the scroll touches the bottom, a state is changing and this causes a re-render.

The thing is, when the component re-renders, it disappears for a few milliseconds and then reset me to top. Do someone know why it happens? I will let the relevant parts of code below if someone can take a look. Also, for those who have time I let a short video on this MediaFire link with the re-render.

THE STATE THAT CHANGES

useEffect(() => {
 const url = `${process.env.REACT_APP_API_URL}/post?limit=${limit}`
 axios
  .get(url)
  .then(({ data }: any) => setPosts(data))
  .catch(err => console.log(err.message))

 return () => setPosts([])
}, [limit])

THE EVENT THAT CHECK IF THE BOTTOM WAS TOUCHED

window.onscroll = function (ev: any) {
 if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
  setLimit(limit + 12)
 }

}

THE RELEVANT PART OF THE JSX

<div className="home__leftSide">
  {posts?.map((post: Post) => (
    <Post post={post} />
  ))}
</div>



Aucun commentaire:

Enregistrer un commentaire