Cause useSWR to refetch on page mount even if key is cached in Next.js

Viewed 1107

So I'm using the useSWR hook to fetch data from my api endpoints. I'm aware that it uses the api routes as the key to cache the data.

The problem is, I am using an api route on 2 pages (let's call them Page1 and Page2), just with different queries. So whenever I visit Page1 first, if I then navigate to page 2, it shows the cached version of page 1 and vice versa.

I tried using the mutate function on both pages and all it does is to first show the cached version before revalidating. Which isn't ideal. What I want is on page mount, the correct data should show.

I also tried setting the revalidateOnMount flag to true in the SWRConfig options in the _app.js like so:

...
   <SWRConfig value={{ revalidateOnMount: true}}>
      ...
    </SWRConfig>
...

Doesn't work.

I should mention that I do have initialData coming from getStaticProps functions on both pages as well.

Would appreciate any bit of help. Been stuck on this for quite some time.

1 Answers

As @juliomalves pointed out above, you can pass multiple arguments to the hook and they both become the key to the cached data.

Related