mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
ready to test
Testing Signed-off-by: Kenneth Obsequio <k80308392@gmail.com>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { createContext, useCallback, useContext, useState } from "react";
|
||||
import api from "@/utils/api.util";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const AdminCategoriesContext = createContext(null);
|
||||
|
||||
export function AdminCategoriesProvider({ children }) {
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [category, setCategory] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const wrap = 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 fetchCategories = useCallback((archived = false) => wrap(async () => {
|
||||
const { data } = await api.get("/admin/categories", { params: { archived } });
|
||||
setCategories(data.data ?? []);
|
||||
return data.data;
|
||||
}), [wrap]);
|
||||
|
||||
const fetchCategory = useCallback((id) => wrap(async () => {
|
||||
const { data } = await api.get(`/admin/categories/${id}`);
|
||||
setCategory(data.data ?? null);
|
||||
return data.data;
|
||||
}), [wrap]);
|
||||
|
||||
const createCategory = useCallback((payload) => wrap(async () => {
|
||||
const { data } = await api.post("/admin/categories", payload);
|
||||
toast.success("Category created.");
|
||||
return data.data;
|
||||
}), [wrap]);
|
||||
|
||||
const updateCategory = useCallback((id, payload) => wrap(async () => {
|
||||
const { data } = await api.put(`/admin/categories/${id}`, payload);
|
||||
setCategory(data.data ?? null);
|
||||
toast.success("Category updated.");
|
||||
return data.data;
|
||||
}), [wrap]);
|
||||
|
||||
const archiveCategory = useCallback((id) => wrap(async () => {
|
||||
await api.delete(`/admin/categories/${id}`);
|
||||
setCategories((prev) => prev.filter((c) => c.id !== id));
|
||||
toast.success("Category archived.");
|
||||
return true;
|
||||
}), [wrap]);
|
||||
|
||||
const restoreCategory = useCallback((id) => wrap(async () => {
|
||||
await api.post(`/admin/categories/${id}/restore`);
|
||||
setCategories((prev) => prev.filter((c) => c.id !== id));
|
||||
toast.success("Category restored.");
|
||||
return true;
|
||||
}), [wrap]);
|
||||
|
||||
return (
|
||||
<AdminCategoriesContext.Provider value={{
|
||||
categories, category, loading,
|
||||
fetchCategories, fetchCategory,
|
||||
createCategory, updateCategory,
|
||||
archiveCategory, restoreCategory,
|
||||
}}>
|
||||
{children}
|
||||
</AdminCategoriesContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useCategories = () => useContext(AdminCategoriesContext);
|
||||
Reference in New Issue
Block a user