Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  104] [ 2]  / answers: 1 / hits: 27354  / 4 Years ago, fri, may 22, 2020, 12:00:00

When attempting shallow routing with a dynamic route in Next.js the page is refreshed and shallow ignored. Seems a lot of people are confused about this.


Say we start on the following page


router.push(
'/post/[...slug]',
'/post/2020/01/01/hello-world',
{ shallow: true }
);

Then we route to another blog post:


router.push(
'/post/[...slug]',
'/post/2020/01/01/foo-bar',
{ shallow: true }
);

This does not trigger shallow routing, the browser refreshes, why?


In the codebase its very clear that this is a feature:


// If asked to change the current URL we should reload the current page
// (not location.reload() but reload getInitialProps and other Next.js stuffs)
// We also need to set the method = replaceState always
// as this should not go into the history (That's how browsers work)
// We should compare the new asPath to the current asPath, not the url
if (!this.urlIsNew(as)) {
method = 'replaceState'
}

I can achieve the same manually using window.history.pushState() although this would of course be a bad idea:


window.history.pushState({
as: '/post/2020/01/01/foo-bar',
url: '/post/[...slug]',
options: { shallow: true }
}, '', '/post/2020/01/01/foo-bar');

As the internal API of Next.JS could change at any time... I may be missing something... but why is shallow ignored in the case? Seems odd.


More From » reactjs

 Answers
11

I think this is the expected behavior because you are routing to a new page. If you are just changing the query parameters shallow routing should work for example:


router.push('/?counter=10', undefined, { shallow: true })

but you are using route parameters


router.push(
'/post/[...slug]',
'/post/2020/01/01/hello-world',
{ shallow: true }
);

That indicates you are routing to a new page, it'll unload the current page, load the new one, and wait for data fetching even though we asked to do shallow routing and this is mentioned in the docs here Shallow routing caveats.


By the way, you say "the page is refreshed" but router.push doesn't refresh the page even when used without shallow: true. It's a single page app after all. It just renders the new page and runs getStaticProps, getServerSideProps, or getInitialProps.


[#50932] Monday, May 11, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;