I load a list of posts on an index page and I want to edit a post on an edit page.
I want to use the mutate function on the edit page, so the edited post is shown on the index page before the new data is fetched from the server. To do this I use the mutate function on the edit page:
mutate(
"api/posts",
posts => {
console.log("posts", posts); // posts are empty on dynamic routes
return {...};
},
false
);
The arrow function displays the correct cached data with a normal next route, e.g., pages/index and pages/edit.
But when the edit page is dynamic, e.g., pages/[postID]/edit, posts` is undefined.
I would expect that I can access posts with dynamic routes as well as with static ones.
CodeSandbox Example
Unfortunately dynamic routing seems not to be working on CodeSandbox. Here is a workaround to test it locally in 2min.
npm install in the directory.npm run dev to start the dev server.success example first. You see the data displayed in the console.fail_index version with the dynamic route. See how undefined is displayed.SWR Version 0.2.3
Next 9.4.4
Try changing your links to work this way:
<Link href="fail/[id]/create" as="fail/123/create">
And let me know if that works.
@sergiodxa It works! Wow, cool.
Can you briefly explain why it works now?
This is because how Next.js Link works, the href must be the route file path, in your case that is fail/[id]/create, and the as is how the URL is going to be displayed in the URL, in your case is fail/123/create, replacing the params with values there, so you can't use the params with value in href, on in as, and when you don't follow this rule and pass fail/123/create Next will try to find a pages/fail/123/create.js file, because it doesn't exists it will reload the page to attempt to render a 404, but when reloading it will correctly find the page file and render the page, and because of the reload the cache of SWR was reseted and you lost your already prefetched data.
Most helpful comment
Try changing your links to work this way:
And let me know if that works.