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

detail.tsx

152 lines4.2 KB

1import * as React from 'react'
2import { Link, useLoaderData } from 'react-router'
3import {
4 noop,
5 onlineManager,
6 useMutation,
7 useQuery,
8 useQueryClient,
9} from '@tanstack/react-query'
10import { moviesMutations, moviesQueries } from '../services/movies/queries'
11import type { LoaderFunctionArgs } from 'react-router'
12import type { QueryClient } from '@tanstack/react-query'
13​
14export const loader =
15 (queryClient: QueryClient, isRestoring: () => boolean) =>
16 async ({ params }: LoaderFunctionArgs) => {
17 if (!params.movieId) {
18 throw new Error('No movie ID provided')
19 }
20 const { queryKey } = moviesQueries.detail(params.movieId)
21 if (
22 !queryClient.getQueryData(queryKey) &&
23 // do not load if we are offline or hydrating because it returns a promise that is pending until we go online again
24 // we just let the Detail component handle it
25 onlineManager.isOnline() &&
26 !isRestoring()
27 ) {
28 await queryClient.query(moviesQueries.detail(params.movieId)).catch(noop)
29 }
30 return { movieId: params.movieId }
31 }
32​
33export default function Detail() {
34 const { movieId } = useLoaderData<ReturnType<typeof loader>>()
35 const queryClient = useQueryClient()
36 const movieQuery = useQuery(moviesQueries.detail(movieId))
37​
38 const [commentDraft, setCommentDraft] = React.useState<string | undefined>()
39​
40 const updateMovie = useMutation({
41 ...moviesMutations.update(),
42 mutationKey: moviesQueries.detail(movieId).queryKey,
43 onMutate: async (variables) => {
44 await queryClient.cancelQueries({
45 queryKey: moviesQueries.detail(movieId).queryKey,
46 })
47 const { queryKey } = moviesQueries.detail(movieId)
48 const previousData = queryClient.getQueryData(queryKey)
49​
50 // remove local state so that server state is taken instead
51 setCommentDraft(undefined)
52​
53 queryClient.setQueryData(
54 queryKey,
55 (old) =>
56 old && {
57 ...old,
58 movie: {
59 ...old.movie,
60 comment: variables.comment,
61 },
62 },
63 )
64​
65 return { previousData }
66 },
67 onError: (_, __, onMutateResult) => {
68 queryClient.setQueryData(
69 moviesQueries.detail(movieId).queryKey,
70 onMutateResult?.previousData,
71 )
72 },
73 onSettled: () => {
74 queryClient.invalidateQueries({
75 queryKey: moviesQueries.detail(movieId).queryKey,
76 })
77 },
78 })
79​
80 const comment = commentDraft ?? movieQuery.data?.movie.comment
81​
82 if (movieQuery.isLoading) {
83 return 'Loading...'
84 }
85​
86 function submitForm(event: any) {
87 event.preventDefault()
88​
89 if (comment === undefined) {
90 return
91 }
92​
93 updateMovie.mutate({
94 id: movieId,
95 comment,
96 })
97 }
98​
99 if (movieQuery.data) {
100 return (
101 <form onSubmit={submitForm}>
102 <Link to="/">Back</Link>
103 <h1>Movie: {movieQuery.data.movie.title}</h1>
104 <p>
105 Try to mock offline behavior with the button in the devtools, then
106 update the comment. The optimistic update will succeed, but the actual
107 mutation will be paused and resumed once you go online again.
108 </p>
109 <p>
110 You can also reload the page, which will make the persisted mutation
111 resume, as you will be online again when you "come back".
112 </p>
113 <p>
114 <label>
115 Comment: <br />
116 <textarea
117 name="comment"
118 value={comment}
119 onChange={(event) => setCommentDraft(event.target.value)}
120 />
121 </label>
122 </p>
123 <button type="submit">Submit</button>
124 <div>
125 Updated at: {new Date(movieQuery.data.ts).toLocaleTimeString()}
126 </div>
127 <div>{movieQuery.isFetching && 'fetching...'}</div>
128 <div>
129 {updateMovie.isPaused
130 ? 'mutation paused - offline'
131 : updateMovie.isPending && 'updating...'}
132 </div>
133 </form>
134 )
135 }
136​
137 if (movieQuery.isError) {
138 return (
139 <div>
140 <Link to="/">Back</Link>
141 <h1>Couldn't load movie!</h1>
142 <div>{movieQuery.error.message}</div>
143 </div>
144 )
145 }
146​
147 if (movieQuery.isPaused) {
148 return "We're offline and have no data to show :("
149 }
150​
151 return null