Skip to content

Infinite loop when passing onSuccess: undefined explicitly #4218

@mori-hisayuki

Description

@mori-hisayuki

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions