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

README.md

16 lines1.2 KB

1# TanStack Preact Query Optimistic Updates Example
2​
3Adds todos optimistically in two ways: from the pending mutation's `variables`, or by writing to the cache in `onMutate` and rolling back on error.
4​
5## How it works
6​
7- `src/services/todos/queries.ts` defines `todosQueries.list()`, a `queryOptions` factory keyed by `['todos', 'list']`, and `todosMutations.create()` with `mutationOptions`.
8- `src/components/TodoListUI.tsx` reads the list with `useSuspenseQuery` and renders the pending todo from `addTodoMutation.variables` while `isPending` is `true`, without touching the cache. `onSettled` invalidates the list.
9- `src/components/TodoListCache.tsx` uses `onMutate` to call `cancelQueries`, save the current list with `getQueryData`, and add a todo with an `optimistic-` id through `setQueryData`. `onError` restores the saved list, and `onSettled` invalidates it.
10- `src/components/ApproachTabs.tsx` switches between the two approaches, and `src/App.tsx` wraps them in `Suspense`.
11- `src/mocks.ts` is an MSW handler for `/api/todos`. The POST handler fails about 30% of the time with a 500 so the rollback can be seen.
12​
13To run this example:
14​
15- `npm install`
16- `npm run dev`