examples/react/offline-tanstack-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Offline Example (TanStack Router)#
A movie list that keeps working offline. Queries and mutations are persisted, mutations made offline are paused, and they resume when the connection returns or after a reload.
Built with TanStack Router.
How it works#
src/services/movies/queries.tsdefinesmoviesQueries.list()andmoviesQueries.detail(id)withqueryOptions, andmoviesMutations.update()withmutationOptions, whosemutationFncancels the detail query before posting the comment.src/App.tsxwraps the router inPersistQueryClientProviderwith alocalStoragepersister and registersmoviesMutations.update()withqueryClient.setMutationDefaults(moviesQueries.all(), ...), so mutations restored after a reload still have amutationFn. ItsonSuccesscallsqueryClient.resumePausedMutations()and theninvalidateQueries(), anduseIsRestoringis passed to the router context asisRestoring.- The
loaderinsrc/routes/$movieId.tsxreturns cached data fromqueryClient.getQueryData, and callsqueryClient.queryonly whenonlineManager.isOnline()istrueand the cache is not being restored. OtherwiseuseQueryin the component handles it. src/routes/$movieId.tsxupdates the comment withuseMutationand amutationKeyunder['movies'], writing it optimistically inonMutatewithqueryClient.setQueryDataand rolling back inonError. While offline, the mutationisPausedand the page shows "mutation paused - offline".src/routes/index.tsxreadsuseQuery(moviesQueries.list()).src/mocks.tssets up an MSW worker that servesGET /movies,GET /movies/:id, andPOST /movies/:idwith a 500 ms delay.
To run this example:
npm installnpm run dev