Skip to content

RTK Query - UseLazyQuery method call returns undefined when called from an unmounted component #5173

@MateuszGroth

Description

@MateuszGroth

Preconditions:

Define a query with keepUnusedDataFor: 0, eg.

    getPost: build.query<Post, void>({
      query: () => ({
        url: `/post`,
        method: "GET",
      }),
      keepUnusedDataFor: 0,
    }),

Have a modal, a button or whatever that you can unmount after triggering an action (clicking the CTA or something)

const TestComponentWrapper = () => {
  const [mounted, setMounted] = useState(true);
  if (!mounted) {
    return;
  }

  return <TestComponent unmount={() => setMounted(false)} />;
};

const TestComponent = ({ unmount }: { unmount: () => void }) => {
  const [getPost] = useLazyGetPostQuery();
  const onClick = async () => {
    unmount();
    const response = await getPost().unwrap();
    console.log({ response });
  };
  return <button onClick={onClick}>Test</button>;
};

render

<TestComponentWrapper />

The response in this case is undefined, even if the API returns valid data

I would expect the data to be returned from await getPost().unwrap() even if it's not kept in cache due to keepUnusedDataFor: 0,

"react": "19.2.3",
"react-dom": "19.2.3",
"@reduxjs/toolkit": "2.11.2"

Metadata

Metadata

Assignees

No one assigned

    Labels

    RTK-QueryIssues related to Redux-Toolkit-Queryneeds more infoThe issue still has not been fully clarified.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions