examples/preact/optimistic-updates
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack Preact Query Optimistic Updates Example#
Adds todos optimistically in two ways: from the pending mutation's variables, or by writing to the cache in onMutate and rolling back on error.
How it works#
src/services/todos/queries.tsdefinestodosQueries.list(), aqueryOptionsfactory keyed by['todos', 'list'], andtodosMutations.create()withmutationOptions.src/components/TodoListUI.tsxreads the list withuseSuspenseQueryand renders the pending todo fromaddTodoMutation.variableswhileisPendingistrue, without touching the cache.onSettledinvalidates the list.src/components/TodoListCache.tsxusesonMutateto callcancelQueries, save the current list withgetQueryData, and add a todo with anoptimistic-id throughsetQueryData.onErrorrestores the saved list, andonSettledinvalidates it.src/components/ApproachTabs.tsxswitches between the two approaches, andsrc/App.tsxwraps them inSuspense.src/mocks.tsis an MSW handler for/api/todos. The POST handler fails about 30% of the time with a 500 so the rollback can be seen.
To run this example:
npm installnpm run dev