mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
add: more commits
Signed-off-by: Kenneth Obsequio <k80308392@gmail.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import { createContext, useCallback, useContext, useState } from "react";
|
||||
import api from "@/utils/api.util";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const AdminNotificationTemplateContext = createContext(null);
|
||||
|
||||
export function useAdminNotificationTemplates() {
|
||||
const ctx = useContext(AdminNotificationTemplateContext);
|
||||
if (!ctx) throw new Error("useAdminNotificationTemplates must be used inside AdminNotificationTemplateProvider");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function AdminNotificationTemplateProvider({ children }) {
|
||||
const [templates, setTemplates] = useState([]);
|
||||
const [template, setTemplate] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const request = useCallback(async (fn) => {
|
||||
setLoading(true);
|
||||
try { return await fn(); }
|
||||
catch (err) {
|
||||
toast.error(err?.response?.data?.message ?? "Something went wrong.");
|
||||
return null;
|
||||
} finally { setLoading(false); }
|
||||
}, []);
|
||||
|
||||
const fetchTemplates = useCallback(() =>
|
||||
request(async () => {
|
||||
const { data } = await api.get("/admin/notification-templates");
|
||||
setTemplates(data.data ?? []);
|
||||
return data.data;
|
||||
}), [request]);
|
||||
|
||||
const fetchTemplate = useCallback((id) =>
|
||||
request(async () => {
|
||||
const { data } = await api.get(`/admin/notification-templates/${id}`);
|
||||
setTemplate(data.data ?? null);
|
||||
return data.data;
|
||||
}), [request]);
|
||||
|
||||
const updateTemplate = useCallback((id, payload) =>
|
||||
request(async () => {
|
||||
const { data } = await api.put(`/admin/notification-templates/${id}`, payload);
|
||||
setTemplates((prev) =>
|
||||
prev.map((t) => (String(t.notification_template_id) === String(id) ? data.data : t))
|
||||
);
|
||||
if (template && String(template.notification_template_id) === String(id)) setTemplate(data.data);
|
||||
toast.success("Notification template updated.");
|
||||
return data.data;
|
||||
}), [request, template]);
|
||||
|
||||
return (
|
||||
<AdminNotificationTemplateContext.Provider value={{
|
||||
templates, template, loading,
|
||||
fetchTemplates, fetchTemplate, updateTemplate,
|
||||
}}>
|
||||
{children}
|
||||
</AdminNotificationTemplateContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user