-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Open
Description
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
onSuccessproperty is omitted entirely onError: undefinedis passed instead- An empty function
() => {}is passed asonSuccess
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 fineWorkaround: 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
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels