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

README.md

16 lines1.1 KB

1# TanStack Lit 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/todo-list-ui.ts` reads the list with `createQueryController` and renders the pending todo from the mutation's `variables` while `isPending` is `true`, without touching the cache. `onSettled` invalidates the list.
9- `src/todo-list-cache.ts` uses `onMutate` on its `createMutationController` 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/approach-tabs.ts` switches between the two elements.
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`