Passing an updated fetcher method has no effect
See original GitHub issueBug report
Description / Observed Behavior
Passing an updated fetcher method to useSWR
has no effect. The initial version of the fetcher will be used.
I am passing a fetcher function to useSWR
that is updated by applying a new access token.
const [accessToken, setAccessToken] = useState("valid-0");
const fetcher = () => {
console.log("fetch with token:", accessToken);
};
const swrWithOutdatedFetcher = useSWR("key", fetcher);
When I call setAccessToken("valid-1")
at some point (and revalidate), the output will still be "fetch with token: valid-0"
.
Expected Behavior
I was expecting swr to use the updated fetcher method. I believe this is the expected way when working with hooks in react.
In my example I’d expect "fetch with token: valid-1"
.
The workaround for now is to use useRef
in combination with useEffect
and then call fetcherRef.currect()
.
const fetcherRef = useRef(fetcher);
useEffect(() => {
fetcherRef.current = fetcher;
});
const swrWithUpdatedFetcher = useSWR("key", () => fetcherRef.current());
If this behavior is intended, some words about this is the docs would be helpful and appreciated.
Repro Steps / Code Example
A simple example to reproduce and also the workaround using useRef
:
https://codesandbox.io/s/autumn-butterfly-c4xe2?file=/src/App.tsx
Additional Context
SWR version 0.5.5
Related: #515 #927 https://github.com/vercel/swr/blob/3d380e21fed1f41b7df7816c55216945bf80eae9/src/use-swr.ts#L479-L486
Issue Analytics
- State:
- Created 2 years ago
- Reactions:3
- Comments:7 (2 by maintainers)
➕1 on that. FWIW; I know several developers that didn’t understand that the fetcher instance that was first used as the fetcher for that set of keys (and component?) will be used for all/most subsequent request (for that set of keys).
Is it possible to add some information about this to the Data fetching page? It feels like 99% of the time when we pass a fetcher directly to
useSWR
we do it the wrong way, it is likely better to configure the fetch using the global configuration.Would love to accept a PR to improve this! 👍