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 :)
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 :)
Share Improve this question edited Apr 22, 2020 at 8:55 Mileta Dulovic asked Apr 22, 2020 at 8:48 Mileta DulovicMileta Dulovic 1,0641 gold badge17 silver badges38 bronze badges1 Answer
Reset to default 15When 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]);
}