Bug report
Description / Observed Behavior
When onSuccess: undefined is explicitly passed as a property in the useSWR options, it causes infinite requests. This issue does not occur when:
- The
onSuccess property is omitted entirely
onError: undefined is passed instead
- An empty function
() => {} is passed as onSuccess
Expected Behavior
onSuccess: undefined should behave the same as omitting the onSuccess property entirely.
Repro Steps / Code Example
// ❌ Causes infinite loop
const { data } = useSWR(key, fetcher, {
onSuccess: undefined,
});
// ✅ Works fine when onSuccess is omitted
const { data } = useSWR(key, fetcher);
// ✅ onError: undefined does not cause the issue
const { data } = useSWR(key, fetcher, {
onError: undefined,
});
// ✅ Works fine with an empty function
const { data } = useSWR(key, fetcher, {
onSuccess: () => {},
});
A common scenario where this occurs is when a custom hook accepts an optional onSuccess callback and passes it directly to useSWR:
const useMyFetch = ({ onSuccess }: { onSuccess?: (data: Data) => void }) => {
return useSWR(key, fetcher, {
onSuccess, // becomes undefined when the caller doesn't provide it
});
};
useMyFetch({}); // → infinite loop
useMyFetch({ onSuccess: (data) => console.log(data) }); // → works fine
Workaround: Strip undefined values from the options object before passing it to useSWR.
const sanitizedConfig = Object.fromEntries(
Object.entries(config).filter(([, v]) => v !== undefined)
);
Additional Context
SWR version: ^2.3.8
Bug report
Description / Observed Behavior
When
onSuccess: undefinedis explicitly passed as a property in theuseSWRoptions, it causes infinite requests. This issue does not occur when:onSuccessproperty is omitted entirelyonError: undefinedis passed instead() => {}is passed asonSuccessExpected Behavior
onSuccess: undefinedshould behave the same as omitting theonSuccessproperty entirely.Repro Steps / Code Example
A common scenario where this occurs is when a custom hook accepts an optional
onSuccesscallback and passes it directly touseSWR:Workaround: Strip
undefinedvalues from the options object before passing it touseSWR.Additional Context
SWR version:
^2.3.8