50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
import {
|
|
useGetMePreferences,
|
|
useUpdateMePreferences,
|
|
getGetMePreferencesQueryKey,
|
|
getGetMeWatchlistQueryKey,
|
|
} from "@workspace/api-client-react";
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { useAuth } from "@/hooks/use-auth";
|
|
|
|
export function useWatchlist() {
|
|
const { isAuthenticated, hasFeature } = useAuth();
|
|
const queryClient = useQueryClient();
|
|
|
|
const canWatchlist = isAuthenticated && hasFeature("watchlist");
|
|
|
|
const { data: prefs, isLoading } = useGetMePreferences({
|
|
query: { queryKey: getGetMePreferencesQueryKey(), enabled: canWatchlist, retry: false },
|
|
});
|
|
|
|
const update = useUpdateMePreferences();
|
|
|
|
const watchlist = prefs?.watchlist ?? [];
|
|
|
|
function invalidate() {
|
|
queryClient.invalidateQueries({ queryKey: getGetMePreferencesQueryKey() });
|
|
queryClient.invalidateQueries({ queryKey: getGetMeWatchlistQueryKey() });
|
|
}
|
|
|
|
function toggle(id: number) {
|
|
const next = watchlist.includes(id) ? watchlist.filter((x) => x !== id) : [...watchlist, id];
|
|
update.mutate(
|
|
{ data: { watchlist: next } },
|
|
{
|
|
onSuccess: () => invalidate(),
|
|
onError: () => invalidate(),
|
|
},
|
|
);
|
|
}
|
|
|
|
const isWatched = (id: number) => watchlist.includes(id);
|
|
|
|
return {
|
|
watchlist,
|
|
toggle,
|
|
isWatched,
|
|
canWatchlist,
|
|
isLoading: canWatchlist && isLoading,
|
|
};
|
|
}
|