Swr: Mutation not working correct on dynamic pages

Created on 7 Jul 2020  路  3Comments  路  Source: vercel/swr

Bug report

Description / Observed Behavior

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.

Expected Behavior

I would expect that I can access posts with dynamic routes as well as with static ones.

Repro Steps / Code Example

CodeSandbox Example
Unfortunately dynamic routing seems not to be working on CodeSandbox. Here is a workaround to test it locally in 2min.

  • Go to CodeSandbox and export to .ZIP

    • Unpack the ZIP and run npm install in the directory.

    • Run npm run dev to start the dev server.

    • Open the console and test the success example first. You see the data displayed in the console.

    • Now run the fail_index version with the dynamic route. See how undefined is displayed.

Additional Context

SWR Version 0.2.3
Next 9.4.4

Most helpful comment

Try changing your links to work this way:

<Link href="fail/[id]/create" as="fail/123/create">

And let me know if that works.

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings