examples/svelte/optimistic-updates-sveltekit
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack Svelte Query Optimistic Updates Example (SvelteKit)#
Adds todos optimistically by writing to the cache in onMutate and rolling back on error.
Built with SvelteKit.
How it works#
src/lib/services/todos/queries.tsdefinestodosQueries.list()withqueryOptions, keyed by['todos', 'list'], andtodosMutations.create()withmutationOptions.src/lib/services/todos/api.tscalls/api/data.src/routes/+page.sveltereads the list withcreateQueryand adds todos withcreateMutation. InonMutateit cancels the list query, saves the current data and writes the new todo into the cache withclient.setQueryData.- If the mutation fails,
onErrorrestores the saved data.onSettledinvalidates the list either way, so it is refetched from the server. src/routes/api/data/+server.tsis a SvelteKit endpoint that keeps the todos in server memory.GETwaits 1 second, andPOSTuppercases the text and fails about 30% of the time.
To run this example:
npm installnpm run dev