Open History to see the last commit
1import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2import * as api from "./api";
3import * as React from "react";
4β
5export const movieKeys = {
6 all: () => ["movies"],
7 list: () => [...movieKeys.all(), "list"],
8 details: () => [...movieKeys.all(), "detail"],
9 detail: (id) => [...movieKeys.details(), id],
10};
11β
12export const useMovie = (movieId) => {
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();
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 };
55};