The weeb for the next gen discord boat - Wamellow wamellow.com
bot discord
at master 1.1 kB view raw
1import { cacheOptions, getData } from "@/lib/api"; 2import { useCallback } from "react"; 3import { useQuery, useQueryClient } from "react-query"; 4 5export type ApiEdit<T> = <K extends keyof T>(key: K, value: T[K]) => void; 6 7export function useApi<T>(url: string, enabled?: boolean) { 8 9 const { data, isLoading, error, ...props } = useQuery( 10 url, 11 () => getData<T>(url), 12 { 13 enabled: enabled || true, 14 ...cacheOptions 15 } 16 ); 17 18 const queryClient = useQueryClient(); 19 20 const edit = useCallback( 21 <K extends keyof T>(key: K, value: T[K]) => { 22 queryClient.setQueryData<T>(url, () => ({ 23 ...data, 24 [key]: value 25 } as T)); 26 }, 27 [data] 28 ); 29 30 if (data && typeof data === "object" && "message" in data && typeof data.message === "string") { 31 return { data: undefined, isLoading, error: data.message || "unknown error", edit, ...props }; 32 } 33 34 return { 35 data: data as T, 36 isLoading, 37 error: error ? `${error}` : undefined, 38 edit, 39 ...props 40 }; 41}