File size: 1,554 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import * as React from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import * as api from './api'
export const movieKeys = {
all: () => ['movies'],
list: () => [...movieKeys.all(), 'list'],
details: () => [...movieKeys.all(), 'detail'],
detail: (id: string) => [...movieKeys.details(), id],
}
export const useMovie = (movieId: string) => {
const queryClient = useQueryClient()
const movieQuery = useQuery({
queryKey: movieKeys.detail(movieId),
queryFn: () => api.fetchMovie(movieId),
})
const [comment, setComment] = React.useState<string | undefined>()
const updateMovie = useMutation({
mutationKey: movieKeys.detail(movieId),
onMutate: async () => {
await queryClient.cancelQueries({ queryKey: movieKeys.detail(movieId) })
const previousData = queryClient.getQueryData(movieKeys.detail(movieId))
// remove local state so that server state is taken instead
setComment(undefined)
queryClient.setQueryData(movieKeys.detail(movieId), {
...previousData,
movie: {
...previousData.movie,
comment,
},
})
return { previousData }
},
onError: (_, __, context) => {
queryClient.setQueryData(movieKeys.detail(movieId), context.previousData)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) })
},
})
return {
comment: comment ?? movieQuery.data?.movie.comment,
setComment,
updateMovie,
movieQuery,
}
}
|