examples/vue/optimistic-updates-nuxt4
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack Vue Query Optimistic Updates Example (Nuxt 4)#
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.
Built with Nuxt 4.
How it works#
app/services/todos/queries.tsdefinestodosQueries.list()withqueryOptionsandtodosMutations.create()withmutationOptions.app/services/todos/api.tscalls the server with$fetchand rethrows the server's error message.app/components/TodoListUI.vuerenders the pending todo from the mutation'svariableswhileisPendingistrue, without touching the cache, and invalidates the list inonSettled.app/components/TodoListCache.vuecancels the list query inonMutate, saves the previous list, and adds a temporary todo withqueryClient.setQueryData.onErrorrestores the saved list, andonSettledinvalidates it.app/app.vuesets the page head withuseHeadand rendersapp/components/ApproachTabs.vueinside<Suspense>, so the tab that awaitssuspense()shows the fallback until the list loads.app/plugins/vue-query.tscreates aQueryClientwith a 1-minutestaleTime, dehydrates it intouseState('vue-query')on the server, and hydrates it on the client.server/api/todos.get.tsandserver/api/todos.post.tsare Nitro handlers over the in-memory list inserver/utils/todos.ts. The POST handler waits 500 ms and fails about 30% of the time, so the rollback is easy to see.
To run this example:
npm installnpm run dev