Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

README.md

61 lines2.0 KB

1# TanStack Query β€” Next.js App Router Optimistic Updates
2​
3This example demonstrates **optimistic updates** with TanStack Query v5 in a Next.js 14 App Router project.
4​
5## What it shows
6​
7A todo list where items appear in the UI immediately after submission β€” before the server confirms. The server randomly fails ~30% of the time so you can observe automatic rollback behaviour.
8​
9Two approaches are shown side by side via a tab toggle:
10​
11### Approach 1 β€” Via UI Variables (simpler)
12​
13Render the pending item directly from `mutation.variables`. No cache touching required. On error, the pending item simply disappears and an error message is shown.
14​
15```ts
16const mutation = useMutation({ mutationFn: addTodo, onSettled: invalidate })
17​
18// In JSX:
19{mutation.isPending && <li style={{ opacity: 0.5 }}>{mutation.variables}</li>}
20```
21​
22**Best when:** the mutation input maps 1-to-1 to what you'd show while pending.
23​
24### Approach 2 β€” Via Cache Manipulation (`onMutate` + rollback)
25​
26`onMutate` cancels in-flight refetches, snapshots the current cache, and writes an optimistic item directly into the cache. `onError` restores the snapshot.
27​
28```ts
29const mutation = useMutation({
30 mutationFn: addTodo,
31 onMutate: async (text) => {
32 await queryClient.cancelQueries({ queryKey: ['todos'] })
33 const previousTodos = queryClient.getQueryData<Todo[]>(['todos'])
34 queryClient.setQueryData<Todo[]>(['todos'], (old = []) => [
35 ...old,
36 optimistic,
37 ])
38 return { previousTodos }
39 },
40 onError: (_err, _vars, context) => {
41 queryClient.setQueryData(['todos'], context?.previousTodos)
42 },
43 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
44})
45```
46​
47**Best when:** you need fine-grained control or the optimistic shape differs from `mutation.variables`.
48​
49## Running the example
50​
51```bash
52npm install
53npm run dev
54```
55​
56Open [http://localhost:3000](http://localhost:3000).
57​
58## Learn more
59​
60- [TanStack Query β€” Optimistic Updates](https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates)
61- [Next.js App Router](https://nextjs.org/docs/app)