import { useEffect, useState } from "react";
import { getThreadSubscription, setThreadSubscription } from "~/fns/notification-settings";
import { useAction } from "./use-action";
type Thread = { owner: string; repo: string; number: number };
type Subscription = { subscribed: boolean; reason: string };
export function useThreadSubscription(thread: Thread) {
const { owner, repo, number } = thread;
const [state, setState] = useState<Subscription | null>(null);
const action = useAction(setThreadSubscription, { invalidate: false });
useEffect(() => {
let cancelled = false;
getThreadSubscription({ data: { owner, repo, number } })
.then((result) => {
if (!cancelled) setState(result);
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [owner, repo, number]);
async function toggle() {
if (!state) return;
const next = !state.subscribed;
if (await action.run({ data: { owner, repo, number, subscribed: next } })) {
setState({ subscribed: next, reason: "manual" });
}
}
return { state, toggle, pending: action.pending, error: action.error };
}