Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 620
Mileta Dulovic Avatar asked Apr 22 '20 08:04

Mileta Dulovic


People also ask

Why use next JS?

With Next.js though, we can quickly find situations where we need to accommodate many other requirements. Let’s have a look at some patterns to accomplish all that.

Is next JS a React framework?

Next.js is a React framework. So, any of the solutions described for React apps can be applied to a Next.js app. Some will require a bigger flex to get it set up, some will have the tradeoffs redistributed based on Next.js’ own functionalities. But everything is 100% usable, you can pick your poison freely.

Is next JS 100% usable?

Some will require a bigger flex to get it set up, some will have the tradeoffs redistributed based on Next.js’ own functionalities. But everything is 100% usable, you can pick your poison freely.


1 Answers

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]);
}
like image 197
Agney Avatar answered Nov 02 '22 23:11

Agney