-
Notifications
You must be signed in to change notification settings - Fork 27.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Page state is not reset for navigating between dynamic routes #9992
Comments
Yes! I've seen similar confusing behavior when using React.useEffect(() => {
console.log("page initial render");
}, []); It only fires once, even when you change the page, but stay on the same route. I'm not sure if it's wrong, but it's definitely not intuitive in my opinion. It's non-intuitive because it works differently when changing the page, but coming from a different route. |
@BananaWanted I just got this exact issue and thanks to @Janpot he pointed me to this post and tried your solution and it worked for me. I'm not sure if this is a "next router" issue or a react issue, but even with your workaround/solution sometimes the browser back button doesn't work as expected, so I think this should be fixed. |
Great find, suggest docs are updated. For future devs, same should be applied in
|
Thanks for the example with the key props. Makes me think of a resource I read recently from Kent C Dodds on the topic : https://kentcdodds.com/blog/understanding-reacts-key-prop For my need, I have made a bespoke key based on the current timestamp, to ensure to always have a new value :
|
Confirming that Page.getInitialProps = (c) => {
return {
id: String(c.query.id),
key: String(c.query.id),
};
}; Produced the expected mount/unmount effects that @Janpot mentioned. |
Any solution? |
I have this issue also. The suggested solution (adding a key) works for me in development builds but not in full builds. |
I also ran into this problem. Adding key to getStaticProps did the trick. I was able to get this solution to build for production with no issues. |
where is data come from ? i dont get it |
It's wherever you get data from in your implementation. As I understand any unique string could be used in lieu of data.id (though it's still not actually working for me in production, I need to revisit). |
i got something like this, can i put key with data instead of 'prop' example of samuel ? export async function getStaticProps({ params }) { |
seems like this may be happening in my app even when the dynamic part is in the middle of a route thanks for posting a workaround |
I'm using Next version 9.4.4 and this solution isn't working for me |
This comment has been minimized.
This comment has been minimized.
@tmikeschu sorry, I'm a little confused about what you mean. What I currently have is this:
Does this look wrong? I figured another solution to this problem would be to simply enclose the contents of the page within a simple layout component and add a key to that, but it only fixes states within contained components and not the state defined outside, like in my example above. |
@modulizer-lee pardon me. I hadn't seen the version change and the preference for |
OMG this keyed solution is magic! |
Hello, any workaround for this issue with getStaticProps ? |
The problem with using the key prop in getStaticProps is that, while going from one page with dynamic props to another one with different props will work, going back (using window.history.back()) will only show the last page with dynamic props that was reached.
|
I have just come across a solution in my case. My eg. is involving a link from one The solution for me was: export default function SomePage() {
const [something, setSomething] = useState(undefined)
const router = useRouter()
const { id } = router.query
useEffect(() => {
if (id) setSomething(undefined) // remove the old page data every time the id chages
}, [id])
const { data, error } = useSWR( id ? '/api/get/' + id : null, fetch)
useEffect(() => {
if(data) setSomething(data) // the new Page data
}, [data])
return (<div>{something?.whatever}</div>
} |
Due to an issue in NextJS the state of a page might not be properly reset when navigating. Through the use of an event listener this can be mitigated. See: vercel/next.js#9992
Im still having This issue when using getServerSideProps, any updates? |
For me the fix with providing a |
Experiencing this issue on 10.0.1 - the key: fix doesn't work for me either :( does anyone have any suggestions? |
Also experiencing issues with This feels so wrong but it's working and I can't find a better solution. Using export default function Page({
data,
}) {
const router = useRouter();
const uid = useRef(router.query.uid);
/**
* If for some reason this component has stale props from navigating back by
* browser history, reload the entire page.
*
* @see {@link https://github.com/vercel/next.js/issues/9992}
*/
useEffect(() => {
if (router.query.uid != uid.current) {
router.reload();
}
}, [router.query.uid]);
return <div>...</div>;
}
export const getStaticProps = async ({ params, previewData = {} }) => {
const data = await queryByUid('product', params.uid, {
...previewData,
});
return {
props: {
data,
key: params.uid,
},
revalidate: 60,
};
};
export const getStaticPaths = async () => {
const { results } = await queryByType('product');
const paths = results.map((result) => ({
params: {
uid: result.uid,
},
}));
return {
paths,
fallback: false,
};
}; |
The working solution is that from @samuelgoddard adding the |
@mattrosno Sounds like you have a custom |
Is this described somewhere in the docs? I really think it should be in the Data Fetching section. Perhaps as another note to each of the data fetching methods (seeing that some of them are already duplicated, e.g. the note about |
I had the same issue but I only need two stateful components to fully reset so I just added |
This is still happening on When I navigate to a detail page with accepts I'm using |
For my issue, I want the useEffect() to trigger when the params of the dynamic route is change. The solution to this is setting the params as the key to useEffect() hook. |
From the looks of it when using |
In my case the |
In my case I am using link to go from page / to /some_id. When trying to go back to / using the browser arrow the page will not reload again, simply nothing will change. I added console.logs to the components that should be rendered (NewsCard) and all the logs can be found, which is ever weirder. If they were not even having their render() method called it would make a bit more sense. I tried the key param, using useEffect with [route.query.id], and passing a key to the at app.js but nothing worked. Any tips?
|
I think this is different issue than the OP. Cuz However, in the code you've posted, this supposed to be the
Did you mean Can you show you |
In Next 11 it's still not properly reloading/resetting components state when navigating from one dynamic page e.g. Is there any known workaround for this? |
This works thanks a ton ❤️ |
Perfect! this works! |
This worked for me as well. Thank you. To add, just for completeness, the router is the value defined using useRouter
|
Hi, I'm gonna close this as a duplicate of #26270. We have also added a note for this behavior in the documentation here https://nextjs.org/docs/api-reference/next/router#usage |
I tried all the solutions from this topic and not one of them helped me solve the problem with the getStaticProps + browser back button. Only these lines helped to solve the problem. I know it doesn't look very good, but it saved my working day :) |
I've been having this same issue and been able to mostly solve it (in many places) using react For a route that uses a <Page key={'page_' + props.lang}>...</Page> Setting the unique key based on the property seems to let react know to re-render the items... it seems even if the data of the page is different, when there is the same fundamental component, react doesn't know to properly update the components on the page. Figured I'd share what seems to be working for me in a lot of cases. |
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
Bug report
Describe the bug
The page state is not reset for navigation between dynamic routes that served by the same source component.
for example, give page source
/a/[param]/index.js
, when navigating from/a/1
to/a/b
, states on the page won't' be reset.The causing is that for this kind of navigation, what actually happened is the same React Component been rendered with different
props
. Thus react takes it as a component is rerendering itself, and causing the new navigated page receive stale states.To fix it, just add
{key: <composed base on URL routing params> }
to page initial props.To Reproduce
I've created a live example:
Expected behavior
Page should be fully reloaded and states should be reset.
Screenshots
N/A
System information
Additional context
The text was updated successfully, but these errors were encountered: