简体   繁体   中英

NextJS initial state is not updating when routing to same page with different params

This project is using NextJS

I have a page which URL looks like this

localhost:3000/first/second

I call getInitialProps on that page. Data is passed from getInitialProps to the component as it should be and I am setting initial state with that data like this

const Index = ({ data }) => {
  const [state, setState] = useState(data.results)
}

Now when I send the user to

localhost:3000/first/third

getInitialprops is called as it should be. data , that is a parameter of component, is always populated with the latest results from getInitialProps but state isn't. It is populated with previous data that was in it. It is not resetting when I am doing client-side routing. Only when I hard refresh the page.

As suggested on NextJS GitHub I tired adding data.key = data.id , in ```getInitialProps``,` that is always a different number to force state update but it is not working.

Any info will be useful.

Thank you for your time:)

When using NextJS, getInitialProps is called before the page renders only for the first time. On subsequent page renders (client side routing), NextJS executes it on the client, but this means that data is not available before page render.

From the docs :

For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router.

You would require a useEffect to sync state:

const Index = ({ data }) => {
  const [state, setState] = useState(data.results);

  useEffect(() => {
    setState(data.results);
  }, [data]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM