Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

README.md

18 lines1.8 KB

1# TanStack React Query Offline Example (TanStack Router)
2​
3A 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.
4​
5Built with [TanStack Router](https://tanstack.com/router).
6​
7## How it works
8​
9- `src/services/movies/queries.ts` defines `moviesQueries.list()` and `moviesQueries.detail(id)` with `queryOptions`, and `moviesMutations.update()` with `mutationOptions`, whose `mutationFn` cancels the detail query before posting the comment.
10- `src/App.tsx` wraps the router in `PersistQueryClientProvider` with a `localStorage` persister and registers `moviesMutations.update()` with `queryClient.setMutationDefaults(moviesQueries.all(), ...)`, so mutations restored after a reload still have a `mutationFn`. Its `onSuccess` calls `queryClient.resumePausedMutations()` and then `invalidateQueries()`, and `useIsRestoring` is passed to the router context as `isRestoring`.
11- The `loader` in `src/routes/$movieId.tsx` returns cached data from `queryClient.getQueryData`, and calls `queryClient.query` only when `onlineManager.isOnline()` is `true` and the cache is not being restored. Otherwise `useQuery` in the component handles it.
12- `src/routes/$movieId.tsx` updates the comment with `useMutation` and a `mutationKey` under `['movies']`, writing it optimistically in `onMutate` with `queryClient.setQueryData` and rolling back in `onError`. While offline, the mutation `isPaused` and the page shows "mutation paused - offline". `src/routes/index.tsx` reads `useQuery(moviesQueries.list())`.
13- `src/mocks.ts` sets up an MSW worker that serves `GET /movies`, `GET /movies/:id`, and `POST /movies/:id` with a 500 ms delay.
14​
15To run this example:
16​
17- `npm install`
18- `npm run dev`