Skip to content

Passing an updated fetcher method has no effect #1131

@PMudra

Description

@PMudra

Bug 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

swr/src/use-swr.ts

Lines 479 to 486 in 3d380e2

// FIXME:
// `fn` and `config` might be changed during the lifecycle,
// but they might be changed every render like this.
// `useSWR('key', () => fetch('/api/'), { suspense: true })`
// So we omit the values from the deps array
// even though it might cause unexpected behaviors.
// eslint-disable-next-line react-hooks/exhaustive-deps
[key]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions