44 lines
1.7 KiB
TypeScript
44 lines
1.7 KiB
TypeScript
import { useCallback, useEffect, useState } from "react";
|
|
import { groupSettingsGet, groupSettingsUpdate } from "@/lib/client/group-settings";
|
|
import type { ApiResult } from "@/lib/client/fetch-json";
|
|
|
|
export default function useGroupSettings(activeGroupId?: number | null) {
|
|
const [settings, setSettings] = useState({ allowMemberTagManage: false, joinPolicy: "NOT_ACCEPTING" as "NOT_ACCEPTING" | "AUTO_ACCEPT" | "APPROVAL_REQUIRED" });
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState("");
|
|
|
|
function isError<T>(result: ApiResult<T>): result is { error: { code: string; message: string } } {
|
|
return "error" in result;
|
|
}
|
|
|
|
const load = useCallback(async () => {
|
|
if (!activeGroupId) {
|
|
setSettings({ allowMemberTagManage: false, joinPolicy: "NOT_ACCEPTING" });
|
|
setError("");
|
|
return;
|
|
}
|
|
setLoading(true);
|
|
setError("");
|
|
const result = await groupSettingsGet();
|
|
if (isError(result)) setError(result.error.message || "");
|
|
else setSettings(result.data.settings);
|
|
setLoading(false);
|
|
}, [activeGroupId]);
|
|
|
|
const updateSettings = useCallback(async (allowMemberTagManage: boolean, joinPolicy?: "NOT_ACCEPTING" | "AUTO_ACCEPT" | "APPROVAL_REQUIRED") => {
|
|
setLoading(true);
|
|
setError("");
|
|
const result = await groupSettingsUpdate({ allowMemberTagManage, joinPolicy });
|
|
if (isError(result)) setError(result.error.message || "");
|
|
else setSettings(result.data.settings);
|
|
setLoading(false);
|
|
return isError(result) ? false : true;
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
load();
|
|
}, [load]);
|
|
|
|
return { settings, loading, error, updateSettings, reload: load };
|
|
}
|