From b484ddd573e19fa041750477b70d7570371024fa Mon Sep 17 00:00:00 2001 From: Wonsuk Choi Date: Mon, 26 Oct 2026 23:15:51 +0900 Subject: [PATCH] docs(examples/preact): add 'star-wars', 'rick-morty' and 'offline' examples (#12401) * docs(examples/preact): add 'suspense', 'star-wars' and 'rick-morty' examples * ci: apply automated fixes * docs(examples/preact): move 'suspense' out and add 'offline' example --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- docs/config.json | 12 + examples/preact/offline/.gitignore | 27 ++ examples/preact/offline/README.md | 6 + examples/preact/offline/eslint.config.js | 20 + examples/preact/offline/index.html | 16 + examples/preact/offline/package.json | 36 ++ .../preact/offline/public/emblem-light.svg | 13 + .../offline/public/mockServiceWorker.js | 361 ++++++++++++++++++ examples/preact/offline/src/App.tsx | 244 ++++++++++++ examples/preact/offline/src/Toaster.tsx | 50 +++ examples/preact/offline/src/index.tsx | 15 + examples/preact/offline/src/mocks.ts | 60 +++ .../preact/offline/src/services/movies/api.ts | 36 ++ .../offline/src/services/movies/queries.ts | 32 ++ .../offline/src/services/movies/types.ts | 19 + examples/preact/offline/src/toaster.css | 24 ++ examples/preact/offline/tsconfig.json | 21 + examples/preact/offline/vite.config.ts | 6 + examples/preact/rick-morty/.gitignore | 27 ++ examples/preact/rick-morty/README.md | 6 + examples/preact/rick-morty/eslint.config.js | 20 + examples/preact/rick-morty/index.html | 16 + examples/preact/rick-morty/package.json | 28 ++ .../preact/rick-morty/public/emblem-light.svg | 13 + examples/preact/rick-morty/src/App.tsx | 19 + examples/preact/rick-morty/src/Character.tsx | 80 ++++ examples/preact/rick-morty/src/Characters.tsx | 29 ++ examples/preact/rick-morty/src/Episode.tsx | 49 +++ examples/preact/rick-morty/src/Episodes.tsx | 31 ++ examples/preact/rick-morty/src/Home.tsx | 44 +++ examples/preact/rick-morty/src/Layout.tsx | 33 ++ examples/preact/rick-morty/src/index.tsx | 6 + .../rick-morty/src/services/characters/api.ts | 16 + .../src/services/characters/queries.ts | 16 + .../src/services/characters/types.ts | 14 + .../rick-morty/src/services/episodes/api.ts | 16 + .../src/services/episodes/queries.ts | 16 + .../rick-morty/src/services/episodes/types.ts | 11 + .../rick-morty/src/services/locations/api.ts | 11 + .../src/services/locations/queries.ts | 11 + .../src/services/locations/types.ts | 5 + examples/preact/rick-morty/src/styles.css | 27 ++ examples/preact/rick-morty/src/vite-env.d.ts | 1 + examples/preact/rick-morty/tsconfig.json | 21 + examples/preact/rick-morty/vite.config.ts | 7 + examples/preact/star-wars/.gitignore | 27 ++ examples/preact/star-wars/README.md | 6 + examples/preact/star-wars/eslint.config.js | 20 + examples/preact/star-wars/index.html | 16 + examples/preact/star-wars/package.json | 28 ++ .../preact/star-wars/public/emblem-light.svg | 13 + examples/preact/star-wars/src/App.tsx | 19 + examples/preact/star-wars/src/Character.tsx | 72 ++++ examples/preact/star-wars/src/Characters.tsx | 29 ++ examples/preact/star-wars/src/Film.tsx | 49 +++ examples/preact/star-wars/src/Films.tsx | 38 ++ examples/preact/star-wars/src/Home.tsx | 44 +++ examples/preact/star-wars/src/Layout.tsx | 33 ++ examples/preact/star-wars/src/index.tsx | 6 + .../star-wars/src/services/characters/api.ts | 14 + .../src/services/characters/queries.ts | 16 + .../src/services/characters/types.ts | 15 + .../star-wars/src/services/films/api.ts | 14 + .../star-wars/src/services/films/queries.ts | 16 + .../star-wars/src/services/films/types.ts | 12 + .../star-wars/src/services/planets/api.ts | 9 + .../star-wars/src/services/planets/queries.ts | 11 + .../star-wars/src/services/planets/types.ts | 3 + examples/preact/star-wars/src/styles.css | 27 ++ examples/preact/star-wars/src/vite-env.d.ts | 1 + examples/preact/star-wars/tsconfig.json | 21 + examples/preact/star-wars/vite.config.ts | 7 + pnpm-lock.yaml | 251 ++++++++++++ 73 files changed, 2388 insertions(+) create mode 100644 examples/preact/offline/.gitignore create mode 100644 examples/preact/offline/README.md create mode 100644 examples/preact/offline/eslint.config.js create mode 100644 examples/preact/offline/index.html create mode 100644 examples/preact/offline/package.json create mode 100644 examples/preact/offline/public/emblem-light.svg create mode 100644 examples/preact/offline/public/mockServiceWorker.js create mode 100644 examples/preact/offline/src/App.tsx create mode 100644 examples/preact/offline/src/Toaster.tsx create mode 100644 examples/preact/offline/src/index.tsx create mode 100644 examples/preact/offline/src/mocks.ts create mode 100644 examples/preact/offline/src/services/movies/api.ts create mode 100644 examples/preact/offline/src/services/movies/queries.ts create mode 100644 examples/preact/offline/src/services/movies/types.ts create mode 100644 examples/preact/offline/src/toaster.css create mode 100644 examples/preact/offline/tsconfig.json create mode 100644 examples/preact/offline/vite.config.ts create mode 100644 examples/preact/rick-morty/.gitignore create mode 100644 examples/preact/rick-morty/README.md create mode 100644 examples/preact/rick-morty/eslint.config.js create mode 100644 examples/preact/rick-morty/index.html create mode 100644 examples/preact/rick-morty/package.json create mode 100644 examples/preact/rick-morty/public/emblem-light.svg create mode 100644 examples/preact/rick-morty/src/App.tsx create mode 100644 examples/preact/rick-morty/src/Character.tsx create mode 100644 examples/preact/rick-morty/src/Characters.tsx create mode 100644 examples/preact/rick-morty/src/Episode.tsx create mode 100644 examples/preact/rick-morty/src/Episodes.tsx create mode 100644 examples/preact/rick-morty/src/Home.tsx create mode 100644 examples/preact/rick-morty/src/Layout.tsx create mode 100644 examples/preact/rick-morty/src/index.tsx create mode 100644 examples/preact/rick-morty/src/services/characters/api.ts create mode 100644 examples/preact/rick-morty/src/services/characters/queries.ts create mode 100644 examples/preact/rick-morty/src/services/characters/types.ts create mode 100644 examples/preact/rick-morty/src/services/episodes/api.ts create mode 100644 examples/preact/rick-morty/src/services/episodes/queries.ts create mode 100644 examples/preact/rick-morty/src/services/episodes/types.ts create mode 100644 examples/preact/rick-morty/src/services/locations/api.ts create mode 100644 examples/preact/rick-morty/src/services/locations/queries.ts create mode 100644 examples/preact/rick-morty/src/services/locations/types.ts create mode 100644 examples/preact/rick-morty/src/styles.css create mode 100644 examples/preact/rick-morty/src/vite-env.d.ts create mode 100644 examples/preact/rick-morty/tsconfig.json create mode 100644 examples/preact/rick-morty/vite.config.ts create mode 100644 examples/preact/star-wars/.gitignore create mode 100644 examples/preact/star-wars/README.md create mode 100644 examples/preact/star-wars/eslint.config.js create mode 100644 examples/preact/star-wars/index.html create mode 100644 examples/preact/star-wars/package.json create mode 100644 examples/preact/star-wars/public/emblem-light.svg create mode 100644 examples/preact/star-wars/src/App.tsx create mode 100644 examples/preact/star-wars/src/Character.tsx create mode 100644 examples/preact/star-wars/src/Characters.tsx create mode 100644 examples/preact/star-wars/src/Film.tsx create mode 100644 examples/preact/star-wars/src/Films.tsx create mode 100644 examples/preact/star-wars/src/Home.tsx create mode 100644 examples/preact/star-wars/src/Layout.tsx create mode 100644 examples/preact/star-wars/src/index.tsx create mode 100644 examples/preact/star-wars/src/services/characters/api.ts create mode 100644 examples/preact/star-wars/src/services/characters/queries.ts create mode 100644 examples/preact/star-wars/src/services/characters/types.ts create mode 100644 examples/preact/star-wars/src/services/films/api.ts create mode 100644 examples/preact/star-wars/src/services/films/queries.ts create mode 100644 examples/preact/star-wars/src/services/films/types.ts create mode 100644 examples/preact/star-wars/src/services/planets/api.ts create mode 100644 examples/preact/star-wars/src/services/planets/queries.ts create mode 100644 examples/preact/star-wars/src/services/planets/types.ts create mode 100644 examples/preact/star-wars/src/styles.css create mode 100644 examples/preact/star-wars/src/vite-env.d.ts create mode 100644 examples/preact/star-wars/tsconfig.json create mode 100644 examples/preact/star-wars/vite.config.ts diff --git a/docs/config.json b/docs/config.json index 1263384fd3..11fa81a127 100644 --- a/docs/config.json +++ b/docs/config.json @@ -7002,6 +7002,18 @@ { "label": "Devtools Embedded Panel", "to": "framework/preact/examples/devtools-panel" + }, + { + "label": "Star Wars", + "to": "framework/preact/examples/star-wars" + }, + { + "label": "Rick And Morty", + "to": "framework/preact/examples/rick-morty" + }, + { + "label": "Offline Queries and Mutations", + "to": "framework/preact/examples/offline" } ] } diff --git a/examples/preact/offline/.gitignore b/examples/preact/offline/.gitignore new file mode 100644 index 0000000000..4673b022e5 --- /dev/null +++ b/examples/preact/offline/.gitignore @@ -0,0 +1,27 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +pnpm-lock.yaml +yarn.lock +package-lock.json + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/examples/preact/offline/README.md b/examples/preact/offline/README.md new file mode 100644 index 0000000000..1cf8892652 --- /dev/null +++ b/examples/preact/offline/README.md @@ -0,0 +1,6 @@ +# Example + +To run this example: + +- `npm install` +- `npm run dev` diff --git a/examples/preact/offline/eslint.config.js b/examples/preact/offline/eslint.config.js new file mode 100644 index 0000000000..b39d2be6c9 --- /dev/null +++ b/examples/preact/offline/eslint.config.js @@ -0,0 +1,20 @@ +// @ts-check + +import { tanstackConfig } from '@tanstack/eslint-config' +import pluginQuery from '@tanstack/eslint-plugin-query' +// @ts-ignore: no types for eslint-config-preact +import preact from 'eslint-config-preact' +import { defineConfig } from 'eslint/config' + +export default defineConfig([ + ...preact, + ...tanstackConfig, + ...pluginQuery.configs['flat/recommended-strict'], + { + rules: { + 'no-duplicate-imports': 'off', + 'no-redeclare': 'off', + 'no-unused-vars': 'off', + }, + }, +]) diff --git a/examples/preact/offline/index.html b/examples/preact/offline/index.html new file mode 100644 index 0000000000..f3812487ad --- /dev/null +++ b/examples/preact/offline/index.html @@ -0,0 +1,16 @@ + + + + + + + + + TanStack Query Preact Offline Example App + + + +
+ + + diff --git a/examples/preact/offline/package.json b/examples/preact/offline/package.json new file mode 100644 index 0000000000..8dc112e81e --- /dev/null +++ b/examples/preact/offline/package.json @@ -0,0 +1,36 @@ +{ + "name": "@tanstack/query-example-preact-offline", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "test:eslint": "eslint ./src", + "test:types": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/preact-query": "^5.105.0", + "@tanstack/preact-query-devtools": "^5.105.0", + "@tanstack/preact-query-persist-client": "^5.105.0", + "@tanstack/query-async-storage-persister": "^5.105.0", + "@zag-js/preact": "^1.46.0", + "@zag-js/toast": "^1.46.0", + "msw": "^2.15.0", + "preact": "^11.0.1", + "preact-iso": "^2.12.2" + }, + "devDependencies": { + "@preact/preset-vite": "^2.10.6", + "@tanstack/eslint-plugin-query": "^5.105.0", + "eslint": "^9.36.0", + "eslint-config-preact": "^2.0.0", + "typescript": "^5.9.3", + "vite": "^8.3.1" + }, + "msw": { + "workerDirectory": [ + "public" + ] + } +} diff --git a/examples/preact/offline/public/emblem-light.svg b/examples/preact/offline/public/emblem-light.svg new file mode 100644 index 0000000000..a58e69ad5e --- /dev/null +++ b/examples/preact/offline/public/emblem-light.svg @@ -0,0 +1,13 @@ + + + + emblem-light + Created with Sketch. + + + + + + + + \ No newline at end of file diff --git a/examples/preact/offline/public/mockServiceWorker.js b/examples/preact/offline/public/mockServiceWorker.js new file mode 100644 index 0000000000..0c970efc96 --- /dev/null +++ b/examples/preact/offline/public/mockServiceWorker.js @@ -0,0 +1,361 @@ +/* eslint-disable */ +/* tslint:disable */ + +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + */ + +const PACKAGE_VERSION = '2.15.0' +const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e' +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const activeClientIds = new Set() + +addEventListener('install', function () { + self.skipWaiting() +}) + +addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()) +}) + +addEventListener('message', async function (event) { + const clientId = Reflect.get(event.source || {}, 'id') + + if (!clientId || !self.clients) { + return + } + + const client = await self.clients.get(clientId) + + if (!client) { + return + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + switch (event.data) { + case 'KEEPALIVE_REQUEST': { + sendToClient(client, { + type: 'KEEPALIVE_RESPONSE', + }) + break + } + + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: { + packageVersion: PACKAGE_VERSION, + checksum: INTEGRITY_CHECKSUM, + }, + }) + break + } + + case 'MOCK_ACTIVATE': { + activeClientIds.add(clientId) + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: { + client: { + id: client.id, + frameType: client.frameType, + }, + }, + }) + break + } + + case 'CLIENT_CLOSED': { + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + + break + } + } +}) + +addEventListener('fetch', function (event) { + const requestInterceptedAt = Date.now() + + // Bypass navigation requests. + if (event.request.mode === 'navigate') { + return + } + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if ( + event.request.cache === 'only-if-cached' && + event.request.mode !== 'same-origin' + ) { + return + } + + // Bypass all requests when there are no active clients. + // Prevents the self-unregistered worked from handling requests + // after it's been terminated (still remains active until the next reload). + if (activeClientIds.size === 0) { + return + } + + const requestId = crypto.randomUUID() + event.respondWith(handleRequest(event, requestId, requestInterceptedAt)) +}) + +/** + * @param {FetchEvent} event + * @param {string} requestId + * @param {number} requestInterceptedAt + */ +async function handleRequest(event, requestId, requestInterceptedAt) { + const client = await resolveMainClient(event) + const requestCloneForEvents = event.request.clone() + const response = await getResponse( + event, + client, + requestId, + requestInterceptedAt, + ) + + // Send back the response clone for the "response:*" life-cycle events. + // Ensure MSW is active and ready to handle the message, otherwise + // this message will pend indefinitely. + if (client && activeClientIds.has(client.id)) { + const serializedRequest = await serializeRequest(requestCloneForEvents) + + // Omit the body of server-sent event stream responses. + // Cloning such responses would prevent client-side stream cancelations + // from reaching the original stream (a teed stream only cancels its + // source once both of its branches cancel) and would buffer the + // entire stream into the unconsumed clone indefinitely. + const isEventStreamResponse = response.headers + .get('content-type') + ?.toLowerCase() + .startsWith('text/event-stream') + + // Clone the response so both the client and the library could consume it. + const responseClone = isEventStreamResponse ? null : response.clone() + + sendToClient( + client, + { + type: 'RESPONSE', + payload: { + isMockedResponse: IS_MOCKED_RESPONSE in response, + request: { + id: requestId, + ...serializedRequest, + }, + response: { + type: response.type, + status: response.status, + statusText: response.statusText, + headers: Object.fromEntries(response.headers.entries()), + body: responseClone ? responseClone.body : null, + }, + }, + }, + responseClone && responseClone.body + ? [serializedRequest.body, responseClone.body] + : [], + ) + } + + return response +} + +/** + * Resolve the main client for the given event. + * Client that issues a request doesn't necessarily equal the client + * that registered the worker. It's with the latter the worker should + * communicate with during the response resolving phase. + * @param {FetchEvent} event + * @returns {Promise} + */ +async function resolveMainClient(event) { + const client = await self.clients.get(event.clientId) + + if (activeClientIds.has(event.clientId)) { + return client + } + + if (client?.frameType === 'top-level') { + return client + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + return allClients + .filter((client) => { + // Get only those clients that are currently visible. + return client.visibilityState === 'visible' + }) + .find((client) => { + // Find the client ID that's recorded in the + // set of clients that have registered the worker. + return activeClientIds.has(client.id) + }) +} + +/** + * @param {FetchEvent} event + * @param {Client | undefined} client + * @param {string} requestId + * @param {number} requestInterceptedAt + * @returns {Promise} + */ +async function getResponse(event, client, requestId, requestInterceptedAt) { + // Clone the request because it might've been already used + // (i.e. its body has been read and sent to the client). + const requestClone = event.request.clone() + + function passthrough() { + // Cast the request headers to a new Headers instance + // so the headers can be manipulated with. + const headers = new Headers(requestClone.headers) + + // Remove the "accept" header value that marked this request as passthrough. + // This prevents request alteration and also keeps it compliant with the + // user-defined CORS policies. + const acceptHeader = headers.get('accept') + if (acceptHeader) { + const values = acceptHeader.split(',').map((value) => value.trim()) + const filteredValues = values.filter( + (value) => value !== 'msw/passthrough', + ) + + if (filteredValues.length > 0) { + headers.set('accept', filteredValues.join(', ')) + } else { + headers.delete('accept') + } + } + + return fetch(requestClone, { headers }) + } + + // Bypass mocking when the client is not active. + if (!client) { + return passthrough() + } + + // Bypass initial page load requests (i.e. static assets). + // The absence of the immediate/parent client in the map of the active clients + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet + // and is not ready to handle requests. + if (!activeClientIds.has(client.id)) { + return passthrough() + } + + // Notify the client that a request has been intercepted. + const serializedRequest = await serializeRequest(event.request) + const clientMessage = await sendToClient( + client, + { + type: 'REQUEST', + payload: { + id: requestId, + interceptedAt: requestInterceptedAt, + ...serializedRequest, + }, + }, + [serializedRequest.body], + ) + + switch (clientMessage.type) { + case 'MOCK_RESPONSE': { + return respondWithMock(clientMessage.data) + } + + case 'PASSTHROUGH': { + return passthrough() + } + } + + return passthrough() +} + +/** + * @param {Client} client + * @param {any} message + * @param {Array} transferrables + * @returns {Promise} + */ +function sendToClient(client, message, transferrables = []) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel() + + channel.port1.onmessage = (event) => { + if (event.data && event.data.error) { + return reject(event.data.error) + } + + resolve(event.data) + } + + client.postMessage(message, [ + channel.port2, + ...transferrables.filter(Boolean), + ]) + }) +} + +/** + * @param {Response} response + * @returns {Response} + */ +function respondWithMock(response) { + // Setting response status code to 0 is a no-op. + // However, when responding with a "Response.error()", the produced Response + // instance will have status code set to 0. Since it's not possible to create + // a Response instance with status code 0, handle that use-case separately. + if (response.status === 0) { + return Response.error() + } + + const mockedResponse = new Response(response.body, response) + + Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { + value: true, + enumerable: true, + }) + + return mockedResponse +} + +/** + * @param {Request} request + */ +async function serializeRequest(request) { + return { + url: request.url, + mode: request.mode, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + cache: request.cache, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body: await request.arrayBuffer(), + keepalive: request.keepalive, + } +} diff --git a/examples/preact/offline/src/App.tsx b/examples/preact/offline/src/App.tsx new file mode 100644 index 0000000000..8182739edf --- /dev/null +++ b/examples/preact/offline/src/App.tsx @@ -0,0 +1,244 @@ +import { useState } from 'preact/hooks' +import { + MutationCache, + QueryClient, + onlineManager, + useIsRestoring, + useMutation, + useQuery, +} from '@tanstack/preact-query' +import { PreactQueryDevtools } from '@tanstack/preact-query-devtools' +import { PersistQueryClientProvider } from '@tanstack/preact-query-persist-client' +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' +import { LocationProvider, Route, Router, useRoute } from 'preact-iso' + +import { moviesMutations, moviesQueries } from './services/movies/queries' +import { Toaster, toaster } from './Toaster' + +const persister = createAsyncStoragePersister({ + storage: window.localStorage, +}) + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + gcTime: 24 * 60 * 60 * 1000, // 24 hours + staleTime: 2000, + retry: 0, + }, + }, + // configure global cache callbacks to show error toast notifications + mutationCache: new MutationCache({ + onError: (error) => { + toaster.error({ title: error.message }) + }, + }), +}) + +// we need a default mutation function so that paused mutations can resume after a page reload +queryClient.setMutationDefaults(moviesQueries.all(), { + ...moviesMutations.update(), + onSuccess: (data) => { + toaster.success({ title: data.message }) + }, +}) + +export default function App() { + return ( + { + // resume mutations after initial restore from localStorage was successful + queryClient.resumePausedMutations().then(() => { + queryClient.invalidateQueries() + }) + }} + > + + + + + + + + + + ) +} + +function List() { + const isRestoring = useIsRestoring() + const moviesQuery = useQuery(moviesQueries.list()) + + if (moviesQuery.isLoading) { + return 'Loading...' + } + + if (moviesQuery.data) { + return ( +
+

Movies

+

+ Try to mock offline behavior with the button in the devtools. You can + navigate around as long as there is already data in the cache. You'll + get a refetch as soon as you go online again. +

+ +
+ Updated at: {new Date(moviesQuery.data.ts).toLocaleTimeString()} +
+
{moviesQuery.isFetching && 'fetching...'}
+
+ ) + } + + if (moviesQuery.isError) { + return ( +
+

Couldn't load movies!

+
{moviesQuery.error.message}
+
+ ) + } + + // query will be in 'idle' fetchStatus while restoring from localStorage + return null +} + +function Detail() { + const { movieId } = useRoute().params + const movieQuery = useQuery(moviesQueries.detail(movieId)) + + const [commentDraft, setCommentDraft] = useState() + + const updateMovie = useMutation({ + ...moviesMutations.update(), + mutationKey: moviesQueries.detail(movieId).queryKey, + onMutate: async (variables) => { + await queryClient.cancelQueries({ + queryKey: moviesQueries.detail(movieId).queryKey, + }) + const { queryKey } = moviesQueries.detail(movieId) + const previousData = queryClient.getQueryData(queryKey) + + // remove local state so that server state is taken instead + setCommentDraft(undefined) + + queryClient.setQueryData( + queryKey, + (old) => + old && { + ...old, + movie: { + ...old.movie, + comment: variables.comment, + }, + }, + ) + + return { previousData } + }, + onError: (_, __, onMutateResult) => { + queryClient.setQueryData( + moviesQueries.detail(movieId).queryKey, + onMutateResult?.previousData, + ) + }, + onSettled: () => { + queryClient.invalidateQueries({ + queryKey: moviesQueries.detail(movieId).queryKey, + }) + }, + }) + + const comment = commentDraft ?? movieQuery.data?.movie.comment + + if (movieQuery.isLoading) { + return 'Loading...' + } + + function submitForm(event: SubmitEvent) { + event.preventDefault() + + if (comment === undefined) { + return + } + + updateMovie.mutate({ + id: movieId, + comment, + }) + } + + if (movieQuery.data) { + return ( +
+ Back +

Movie: {movieQuery.data.movie.title}

+

+ Try to mock offline behavior with the button in the devtools, then + update the comment. The optimistic update will succeed, but the actual + mutation will be paused and resumed once you go online again. +

+

+ You can also reload the page, which will make the persisted mutation + resume, as you will be online again when you "come back". +

+

+