Swr: Fetcher gets called much more than I expect

Created on 2 Dec 2019  路  10Comments  路  Source: vercel/swr

There seems to be some kind of setInterval or similar which seems to refetch the data, even if it didn't change, which would mean I need to implement a kind of cache myself?

Example app is here https://codesandbox.io/s/vibrant-hamilton-dzgt4

It seems to refetch if you're off the page and reactivate it, but also sometimes just on schedule, or when the component rerenders for another reason

Hope to figure out if I maybe misunderstood it?

Most helpful comment

@Haroenv you can see all the options here https://github.com/zeit/swr#options
revalidateOnFocus is enabled by default, the rest of revalidations are disabled by default, except retry on error.

All 10 comments

Screenshot 2019-12-02 at 17 31 15

here you see in the console that the fetcher was called with the same arguments multiple times

Hi @Haroenv unfortunately I can't reproduce. It's only being called when I refocus on the page (or the preview panel in codesandbox since it's an iframe).

You can disable revalidation on focus by using useSWR(key, fetcher, { revalidateOnFocus: false }) and see if it still refetches.

I didn't see that there were options there, revalidating there indeed doesn't make sense for my use case. Is there API docs somewhere I missed?

@Haroenv you can see all the options here https://github.com/zeit/swr#options
revalidateOnFocus is enabled by default, the rest of revalidations are disabled by default, except retry on error.

That clarifies it, thanks!

Well, making revalidateOnFocus false doesn't really make anysense in the following scenario

I am "on the page" and "focusing" I clicked another Link (takes me to another route/page) it refetch the data .. why?

I think revalidateOnFocus should revalidate on focus and as described, but not when clicking on another route/link!

@sergiodxa

Was your component remounted somehow? SWR revalidate any useSWR call when it鈥檚 mounted, even if data was in cache, to ensure it鈥檚 not stale.

Thanks for your reply @sergiodxa

Well, its not. I am just navigating from a page to another (I am using nextjs for sure)

If your call to useSWR is not inside _app.js it will be remounted after a page change if I鈥檓 not wrong. You could try it, add a useEffect that runs a console.log and it has an empty dependency array, if the component is remounted it will not be logged more than once, if it鈥檚 logged again your component remounted.

Nop, its being logged only once .. when I get back to the page itself but not when I leave to another page.

And sure, its not inside my _app.js file.

Lets say
page1.js => useSWR
page2.js => useSWR

  • First land on page1 it fetches the data
  • Navigating to page2 fetches page1 data and page2 data

Setting revalidateOnFocus to false do the trick, but I don't want to loose the fun from revalidateOnFocus tbh

Was this page helpful?
0 / 5 - 0 ratings