examples/svelte/offline-sveltekit
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack Svelte Query Offline Example (SvelteKit)#
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 SvelteKit.
How it works#
src/lib/services/movies/queries.tsdefinesmoviesQueries.list()andmoviesQueries.detail(id)withqueryOptions, andmoviesMutations.update()withmutationOptions. ThemutationFncancels the detail query throughcontext.client.cancelQueriesbefore posting the comment.src/lib/queryClient.tscreates theQueryClientwith a 24-hourgcTimeand acreateAsyncStoragePersisteronlocalStorage.queryClient.setMutationDefaults(moviesQueries.all(), ...)registers the mutation function, so paused mutations restored after a reload can run.src/routes/+layout.sveltewraps the app inPersistQueryClientProviderand callsqueryClient.resumePausedMutations()once the cache is restored.src/routes/+layout.tsturns off SSR and starts the mock worker in itsloadfunction.src/routes/[movieId]/+page.tsis aloadfunction that callsqueryClient.query(...)only when the movie is not cached andonlineManager.isOnline()istrue.src/routes/+page.svelteandsrc/routes/[movieId]/+page.svelteread the movies withcreateQuery.src/routes/[movieId]/+page.svelteupdates the comment withcreateMutation, writing it to the cache inonMutatewithqueryClient.setQueryData, rolling back inonErrorand invalidating inonSettled. While offline the mutation is paused andisPausedistrue.src/lib/mocks.tsuses MSW in the browser to serve/moviesand/movies/:idfrom an in-memory list with a 500 ms delay.
To run this example:
npm installnpm run dev