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