Skip to content

fix: Safeguard onSuccess callback to prevent errors when undefined#4219

Open
mori-hisayuki wants to merge 1 commit intovercel:mainfrom
mori-hisayuki:fix/prevent-undefined-overriding-default-callbacks
Open

fix: Safeguard onSuccess callback to prevent errors when undefined#4219
mori-hisayuki wants to merge 1 commit intovercel:mainfrom
mori-hisayuki:fix/prevent-undefined-overriding-default-callbacks

Conversation

@mori-hisayuki
Copy link

@mori-hisayuki mori-hisayuki commented Feb 7, 2026

Summary

Fixes an infinite loop caused by explicitly passing onSuccess: undefined in useSWR options.

Problem

When onSuccess: undefined is passed as a config property, it overrides the default noop function during config merging (mergeObjects uses object spread). This causes getConfig().onSuccess(...) to throw a TypeError, which is caught internally and triggers an error retry, resulting in an infinite request loop.

This commonly occurs 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
  });
};

Fix

Added optional chaining (?.) to the onSuccess invocation in use-swr.ts so that an undefined callback is safely skipped instead of throwing.

Related issue

Closes #4218

@codesandbox-ci
Copy link

codesandbox-ci bot commented Feb 7, 2026

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@mori-hisayuki mori-hisayuki marked this pull request as ready for review February 7, 2026 17:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Infinite loop when passing onSuccess: undefined explicitly

1 participant