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

movies.js

62 lines1.6 KB

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