Whenever the user clicks on the continue button, a function is fired and in that function, I call:
push("/signup/page-2", undefined, { shallow: true });
All dynamic routes that looks like /signup/[page].js
that returns <Component />
I also have a /signup/index.js
that returns <Component />
The Problem is:
The page reloads and all state is cleared each time push("/signup/page-2", undefined, { shallow: true });
is called.
It's also worth mentioning that this app was a CRA with react-router-dom app that was converted to a next.js app
You got it all wrong about shallow-routing
. Shallow-routing works for the same page URL and generally, you will update the query string parameters for the same page and the updated value of query params will be available through the router
.
router.push('/signup/[page]', '/signup/page-1')
will push the new URL path and will navigate to a complete different page from /signup/
. That is why shallow-routing doesn't work here and the state
value resets.
In the pages directory /signup/[page].js
and /signup/index.js
are two completely different files in the file system. If you try to navigate between them with shallow-routing it will not work.
Solution
You don't need another dynamic route like /signup/[page]
here, you can update the page
param through query string and keep the same URL path. In /signup/index.js
page you can get the updated value of the query param and work on it.
router.push({
pathname: '/signup',
query: {
pageId: "page-1" // update the query param
}
}, undefined, { shallow: true})
// you have access to the updated value of pageId through router.query.pageId
const currPage = router.query.pageId