Open History to see the last commit
1import { createSignal } from 'solid-js'
2import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-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],
10}
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] = createSignal<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<
27 Awaited<ReturnType<typeof api.fetchMovie>>
28 >(movieKeys.detail(movieId))
29β
30 // remove local state so that server state is taken instead
31 setComment(undefined)
32β
33 queryClient.setQueryData(movieKeys.detail(movieId), {
34 ...previousData,
35 movie: {
36 ...previousData?.movie,
37 comment: comment(),
38 },
39 })
40β
41 return { previousData }
42 },
43 onError: (_: any, __: any, context: any) => {
44 queryClient.setQueryData(movieKeys.detail(movieId), context.previousData)
45 },
46 onSettled: () => {
47 queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) })
48 },
49 }))
50β
51 return {
52 comment: () => comment() ?? movieQuery.data?.movie.comment,
53 setComment,
54 updateMovie,
55 movieQuery,
56 }
57}