Skip to content

tRPC v11 useQuery returns stale data after mutation invalidation with optimistic updates in Next.js App Router #7339

@Vansh1811

Description

@Vansh1811

Provide environment information

System:
  OS: Linux 5.15
  CPU: x64
  Memory: 16 GB
Binaries:
  Node: 20.11.0
  npm: 10.2.4
npmPackages:
  typescript: 5.4.5
  next: 14.2.3
  react: 18.3.1
  @trpc/server: 11.0.0-rc.446
  @trpc/client: 11.0.0-rc.446
  @trpc/react-query: 11.0.0-rc.446
  @trpc/next: 11.0.0-rc.446
  @tanstack/react-query: 5.40.0

Describe the bug

When using trpc.utils.invalidate() after a mutation with optimistic updates enabled, the useQuery hook continues to display stale data instead of re-fetching fresh data from the server.

Expected behavior: After calling invalidate(), the query should re-fetch and show updated data.

Actual behavior: The query remains stale and shows cached/optimistic data even after invalidation. The refetch only works on page reload.

Reproduction steps:

  1. Set up a tRPC router with a list query and add mutation
  2. Enable optimistic updates via onMutate in useMutation
  3. After mutation succeeds, call utils.posts.list.invalidate()
  4. Observe that the query data remains stale
const utils = trpc.useUtils();
const addPost = trpc.posts.add.useMutation({
  onMutate: async (newPost) => {
    await utils.posts.list.cancel();
    const prev = utils.posts.list.getData();
    utils.posts.list.setData(undefined, (old) => [...(old ?? []), newPost]);
    return { prev };
  },
  onSettled: () => {
    utils.posts.list.invalidate(); // Does not trigger refetch
  },
});

Link to reproduction

https://github.com/Vansh1811/trpc-bug-repro

To reproduce

  1. Clone the minimal tRPC + Next.js starter
  2. Add a mutation with onMutate optimistic update and onSettled invalidation
  3. Trigger the mutation from the UI
  4. Check if useQuery refetches automatically
  5. Observe: data remains stale, no refetch occurs

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR fixing this bug!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions