| 1 | "use client"; |
| 2 | |
| 3 | import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; |
| 4 | import { toast } from "sonner"; |
| 5 | import { api, ApiError } from "@/lib/api"; |
| 6 | import { queryKeys } from "@/lib/query"; |
| 7 | import type { WatchlistCreate, WatchlistRule } from "@/lib/types"; |
| 8 | |
| 9 | export function useWatchlist() { |
| 10 | return useQuery({ |
| 11 | queryKey: queryKeys.watchlist, |
| 12 | queryFn: () => api.watchlist(), |
| 13 | }); |
| 14 | } |
| 15 | |
| 16 | export function useCreateWatch() { |
| 17 | const qc = useQueryClient(); |
| 18 | return useMutation({ |
| 19 | mutationFn: (body: WatchlistCreate) => api.createWatch(body), |
| 20 | onSuccess: (rule) => { |
| 21 | qc.invalidateQueries({ queryKey: queryKeys.watchlist }); |
| 22 | toast.success(`Now watching “${rule.label}”`); |
| 23 | }, |
| 24 | onError: (err) => { |
| 25 | if (err instanceof ApiError && err.status === 409) { |
| 26 | toast.error("You're already watching that."); |
| 27 | } else { |
| 28 | toast.error(err instanceof Error ? err.message : "Could not add watch."); |
| 29 | } |
| 30 | }, |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | export function usePatchWatch() { |
| 35 | const qc = useQueryClient(); |
| 36 | return useMutation({ |
| 37 | mutationFn: ({ id, ...body }: { id: number } & Partial<Pick<WatchlistRule, "active" | "priority" | "label">>) => |
| 38 | api.patchWatch(id, body), |
| 39 | onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.watchlist }), |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | export function useDeleteWatch() { |
| 44 | const qc = useQueryClient(); |
| 45 | return useMutation({ |
| 46 | mutationFn: (id: number) => api.deleteWatch(id), |
| 47 | onSuccess: () => { |
| 48 | qc.invalidateQueries({ queryKey: queryKeys.watchlist }); |
| 49 | toast("Removed from watchlist"); |
| 50 | }, |
| 51 | }); |
| 52 | } |