Reputation: 13987
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.
Upvotes: 34
Views: 44608
Reputation: 1689
If avoiding rerenders in nested routes is your problem, the solution could be nesting your pages in a layout component as explained here:
https://nextjs.org/docs/basic-features/layouts
https://adamwathan.me/2019/10/17/persistent-layout-patterns-in-nextjs/
Upvotes: 1
Reputation: 14021
Shallow Routing gives you the ability to update pathname or query params without losing state i.e., only the state of route is changed.. But the condition is, you have to be on the same page(as shown in docs Caveats image).
For that you have to pass the second arg to router.push or Router.push as undefined. Otherwise, new page will be loaded after unloading the first page and you won't get the expected behavior.
I mean shallow routing will no longer be working in terms of pathname changing and that's because we chose to load a new page not only the url. Hope this helps š
Example
import { useEffect } from 'react'
import { useRouter } from 'next/router'
// Current URL is '/'
function Page() {
const router = useRouter()
useEffect(() => {
// Always do navigations after the first render
router.push('/post/[...slug]', undefined, { shallow: true })
}, [])
useEffect(() => {
// The pathname changed!
}, [router.pathname ])
}
export default Page
Upvotes: 5
Reputation: 32757
Actually, based on the docs description, I believe you used this push
function wrongly. See the following codes that come from docs:
import Router from 'next/router'
Router.push(url, as, options)
And the docs said:
url
- The URL to navigate to. This is usually the name of a pageas
- Optional decorator for the URL that will be shown in the browser. Defaults tourl
options
- Optional object with the following configuration options: shallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps. Defaults to false
It means you should pass the exact URL as the first parameter and if you wanna show it as decorating name pass the second parameter and for the third just pass the option, so you should write like below:
router.push(
'/post/2020/01/01/hello-world',
undefined,
undefined
);
For the shallow routing you should use the exact example:
router.push('/?counter=10', undefined, { shallow: true });
In fact, with your code, you create a new route and it is inevitable to refreshing.
Upvotes: 0
Reputation: 2516
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
.
Upvotes: 20
Reputation: 1259
Okay, So this answer based on my first answer(and question clarification):
#1 Question was: This does not trigger shallow routing, the browser refreshes, why?
=> Check my last answer for understand how next.js
dealing with file structures.
#2 If you want to deal with unlimited URL params:
You will have to follow this file structure:
.
āāā pages
ā āāā post
ā ā āāā[...slug].js // or [...slug]/index.js
ā āāā about.js
ā āāā index.js
āāā public
ā āāā ...
āāā .gitignore
āāā package.json
āāā package-lock.json
āāā README.md
[...slug].js:
export default function Post({ post }) {
return (
<div>
<h1>Post is here{}</h1>
{JSON.stringify(post)}
</div>
);
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ["*"] } },
],
fallback: true
};
}
export async function getStaticProps(context) {
console.log("SLUG: ", context);
const { params = [] } = context || {};
const res = await fetch(`https://api.icndb.com/jokes/${params && params.slug[0] || 3}`);
const post = await res.json()
return { props: { post } }
}
./index.js:
import Link from 'next/link';
import Router from 'next/router'
export default function Home() {
const handleClick = e => {
e.preventDefault();
Router.push(
'/post/[...slug]',
'/post/2/2/4',
{ shallow: true }
);
}
return (
<div className="container">
<div>
<Link href="/about">
<a>About</a>
</Link>
</div>
<hr />
<div>
<Link
href={`/post/[...slug]?slug=${2}`}
as={`/post/${2}`}
>
<a>
<span>
Post:
</span>
</a>
</Link>
<hr />
<div>
<button onClick={handleClick}>
Push me
</button>
</div>
</div>
</div>
)
}
Any deep /post/any/url/long/will_return_slugfile
Again!!! in next.js
you have to take care about the file system structure in routing. (As I mentioned in my last answer)
pages/post/[[...slug]].js will match /post, /post/a, /post/a/b, and so on.
Upvotes: 1