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

movies.ts

57 lines1.6 KB

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],
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 }