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

movies.ts

55 lines1.5 KB

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