Open History to see the last commit
TanStack Angular Query Optimistic Updates Example#
Adds todos optimistically by writing to the cache in onMutate and rolling back on error.
How it works#
src/app/services/tasks/queries.tshas two@Injectableclasses:TasksQueries, whoselist()returnsqueryOptions, andTasksMutations, whosecreate()returnsmutationOptions.src/app/services/tasks/api.tsposts to/api/tasks-wrong-urlinstead whenfailMutationistrue.src/app/components/optimistic-updates.component.tsreads the list withinjectQueryand creates the task withinjectMutation.onMutatecancels the list query, saves the previous list, and appends the new task withqueryClient.setQueryData.- In
src/app/components/optimistic-updates.component.ts,onErrorputs the saved list back, andonSettledinvalidates the list so it is refetched from the mock server. The "Fail Mutation" checkbox makes the next mutation fail. src/app/interceptor/tasks-mock.interceptor.tsis anHttpInterceptorFn, registered withwithInterceptorsinsrc/app/app.config.ts, that stores tasks insessionStorageand responds after 1 second. Requests to/api/tasks-wrong-urlget a 500 error.
To run this example:
npm installnpm start