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

movies.ts

85 lines2.2 KB

1import * as React from 'react'
2import {
3 mutationOptions,
4 queryOptions,
5 useMutation,
6 useQuery,
7 useQueryClient,
8} from '@tanstack/react-query'
9import * as api from './api'
10​
11export const movieKeys = {
12 all: () => ['movies'],
13 list: () => [...movieKeys.all(), 'list'],
14 details: () => [...movieKeys.all(), 'detail'],
15 detail: (id: string) => [...movieKeys.details(), id],
17​
18export const movieQueryOptions = (movieId: string) =>
19 queryOptions({
20 queryKey: movieKeys.detail(movieId),
21 queryFn: () => api.fetchMovie(movieId),
22 })
23​
24export const updateMovieMutationOptions = () =>
25 mutationOptions({
26 mutationFn: async (
27 { id, comment }: { id: string; comment: string },
28 context,
29 ) => {
30 // to avoid clashes with our optimistic update when an offline mutation continues
31 await context.client.cancelQueries({ queryKey: movieKeys.detail(id) })
32 return api.updateMovie(id, comment)
33 },
34 })
35​
36export const useMovie = (movieId: string) => {
37 const queryClient = useQueryClient()
38​
39 const movieQuery = useQuery(movieQueryOptions(movieId))
40​
41 const [comment, setComment] = React.useState<string | undefined>()
42​
43 const updateMovie = useMutation({
44 ...updateMovieMutationOptions(),
45 mutationKey: movieKeys.detail(movieId),
46 onMutate: async (variables) => {
47 await queryClient.cancelQueries({ queryKey: movieKeys.detail(movieId) })
48 const { queryKey } = movieQueryOptions(movieId)
49 const previousData = queryClient.getQueryData(queryKey)
50​
51 // remove local state so that server state is taken instead
52 setComment(undefined)
53​
54 queryClient.setQueryData(
55 queryKey,
56 (old) =>
57 old && {
58 ...old,
59 movie: {
60 ...old.movie,
61 comment: variables.comment,
62 },
63 },
64 )
65​
66 return { previousData }
67 },
68 onError: (_, __, onMutateResult) => {
69 queryClient.setQueryData(
70 movieQueryOptions(movieId).queryKey,
71 onMutateResult?.previousData,
72 )
73 },
74 onSettled: () => {
75 queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) })
76 },
77 })
78​
79 return {
80 comment: comment ?? movieQuery.data?.movie.comment,
81 setComment,
82 updateMovie,
83 movieQuery,
84 }