Download react-query/examples/react/offline/src/movies.ts from Devendra174/react-code-dataset: direct link, hf CLI and curl.
- Browser
- Download file 1.55 kB
-
https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-query/examples/react/offline/src/movies.ts
- Command line
-
hf download hf://datasets/Devendra174/react-code-dataset@1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-query/examples/react/offline/src/movies.ts
-
curl -L -o movies.ts https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-query/examples/react/offline/src/movies.ts
1.55 kB
| import * as React from 'react' | |
| import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' | |
| import * as api from './api' | |
| export const movieKeys = { | |
| all: () => ['movies'], | |
| list: () => [...movieKeys.all(), 'list'], | |
| details: () => [...movieKeys.all(), 'detail'], | |
| detail: (id: string) => [...movieKeys.details(), id], | |
| } | |
| export const useMovie = (movieId: string) => { | |
| const queryClient = useQueryClient() | |
| const movieQuery = useQuery({ | |
| queryKey: movieKeys.detail(movieId), | |
| queryFn: () => api.fetchMovie(movieId), | |
| }) | |
| const [comment, setComment] = React.useState<string | undefined>() | |
| const updateMovie = useMutation({ | |
| mutationKey: movieKeys.detail(movieId), | |
| onMutate: async () => { | |
| await queryClient.cancelQueries({ queryKey: movieKeys.detail(movieId) }) | |
| const previousData = queryClient.getQueryData(movieKeys.detail(movieId)) | |
| // remove local state so that server state is taken instead | |
| setComment(undefined) | |
| queryClient.setQueryData(movieKeys.detail(movieId), { | |
| ...previousData, | |
| movie: { | |
| ...previousData.movie, | |
| comment, | |
| }, | |
| }) | |
| return { previousData } | |
| }, | |
| onError: (_, __, context) => { | |
| queryClient.setQueryData(movieKeys.detail(movieId), context.previousData) | |
| }, | |
| onSettled: () => { | |
| queryClient.invalidateQueries({ queryKey: movieKeys.detail(movieId) }) | |
| }, | |
| }) | |
| return { | |
| comment: comment ?? movieQuery.data?.movie.comment, | |
| setComment, | |
| updateMovie, | |
| movieQuery, | |
| } | |
| } | |