examples/react/offline-react-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Offline Example (React 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 React 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().- The
loaderinsrc/routes/detail.tsxfetches the movie withqueryClient.queryonly when it is not cached,onlineManager.isOnline()istrue, and the cache is not being restored. OtherwiseuseQueryin the component handles it. src/routes/detail.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/list.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