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