65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
import { useCallback, useEffect, useState } from "react";
|
|
import type { ApiResult } from "@/lib/client/fetch-json";
|
|
import { inviteLinkAccept, inviteLinkGet, type InviteAcceptResult, type InviteLinkSummary } from "@/lib/client/invite-links";
|
|
|
|
function isError<T>(result: ApiResult<T>): result is { error: { code: string; message: string } } {
|
|
return "error" in result;
|
|
}
|
|
|
|
export default function useInviteLink(token: string | null) {
|
|
const [link, setLink] = useState<InviteLinkSummary | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [accepting, setAccepting] = useState(false);
|
|
const [error, setError] = useState("");
|
|
const [result, setResult] = useState<InviteAcceptResult | null>(null);
|
|
|
|
const load = useCallback(async () => {
|
|
if (!token) {
|
|
setLink(null);
|
|
setError("");
|
|
setResult(null);
|
|
return;
|
|
}
|
|
setLoading(true);
|
|
setError("");
|
|
setResult(null);
|
|
const response = await inviteLinkGet(token);
|
|
if (isError(response)) {
|
|
setError(response.error.message || "");
|
|
setLink(null);
|
|
} else {
|
|
setLink(response.data.link);
|
|
}
|
|
setLoading(false);
|
|
}, [token]);
|
|
|
|
const accept = useCallback(async () => {
|
|
if (!token) return null;
|
|
setAccepting(true);
|
|
setError("");
|
|
const response = await inviteLinkAccept(token);
|
|
if (isError(response)) {
|
|
setError(response.error.message || "");
|
|
setAccepting(false);
|
|
return null;
|
|
}
|
|
setResult(response.data.result);
|
|
setAccepting(false);
|
|
return response.data.result;
|
|
}, [token]);
|
|
|
|
useEffect(() => {
|
|
load();
|
|
}, [load]);
|
|
|
|
return {
|
|
link,
|
|
loading,
|
|
accepting,
|
|
error,
|
|
result,
|
|
accept,
|
|
reload: load
|
|
};
|
|
}
|