Search code examples
reactjsnext.jssetstateuse-effect

Data not displaying when going to previous page next js application


I'm working on a headless wordpress website using nextjs. The site displays a list of posts and lets you see details of each post in a new page when you click on them. When you are in the individual post's page, you can either click a "BACK" button or use the navbar to go back to the home page, where the post list is. My issue is that, if somebody shares the link of one of the posts, lets say https://example.com/example-post the post page shows correctly but when you try to navigate to the home page, it doesn't display the post list unless I refresh the page. I checked and I'm getting the data from wordpress. but the state is not being updated. I'm using useState to update the state:

  useEffect(() => {
    setPosts(data && data.posts.nodes.sort());
  }, []);

It seems as if it is not firing up unless I refresh from the browser directly.


Solution

  • I was able to fix the issue by including data as the trigger for useEffect() like this:

      useEffect(() => {
        setPosts(data && data.posts.nodes.sort());
      }, [data]);