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

$movieId.tsx

141 lines3.9 KB

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