Why does useSWR make 2 calls to the backend for every request?
See original GitHub issueBug report
Description / Observed Behavior
When request happened, swr made 2 call.
First time was old params,
Second is new params.
Expected Behavior
Change one time, request one time. No old params request.
Repro Steps / Code Example
https://codesandbox.io/s/adoring-https-xftf8?file=/pages/index.js
// When currentMenu.market or currentMenu.group or currentMenu.inst changed, send a request to backend.
const { data, error } = useSWR(
currentMenu.inst
? [
"/api/playbackCharts",
currentMenu.market,
currentMenu.group,
currentMenu.inst,
]
: null,
fetcher,
);
Additional Context
SWR version: 1.0.1
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (3 by maintainers)
Top Results From Across the Web
Why useSWRInfinite call my backend twice for every request?
Every time I click it it makes 2 calls to my backend. The first call is with index 0 and the second is...
Read more >Dependent and Conditional Data Fetching With useSWR
Thanks to useSWR, we can save a call to our backend, and automatically respond to any requests for unverified users with an empty...
Read more >SWR: React Hooks for Data Fetching
SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate),...
Read more >Multiple requests in an external API and Auto Revalidate
Hello, i am building an application that should check every second if there is new data in an external API endpoint.
Read more >An Introduction To SWR: React Hooks For Remote Data ...
We already have many ways to make HTTP requests in our React Apps, and two of the most popular is the Fetch API...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Im no master in useSwr but seems like @shuding is correct.
It’s the focusing that causes the calls.
However, you can disable that bt passing a third param to useSwr hook:
const { data, error } = useSWR(
/api/num?num=${2}
, fetcher, { revalidateOnFocus: false });Something like that. 😃
Because SWR has focus revalidation enabled by default, when you are focusing on the code editor and click the button, it is a focus event so the old key will be revalidated. And then the key changes so a new revalidation is started.
I do think it can be improved in this particular scenario, so I’ll keep the issue open. I think the way to fix this is to make focus revalidation async and cancelable.