mirror of
https://github.com/PeterMaquiran/tvone.git
synced 2026-04-18 15:27:52 +00:00
89 lines
1.6 KiB
TypeScript
89 lines
1.6 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import {
|
|
Category,
|
|
getCategoriesTree,
|
|
getCategoriesFlat,
|
|
createCategory,
|
|
updateCategory,
|
|
deleteCategory,
|
|
} from "@/lib/categories.api";
|
|
import { slugify } from "@/lib/slug";
|
|
|
|
export function useCategories() {
|
|
const [tree, setTree] = useState<Category[]>([]);
|
|
const [flat, setFlat] = useState<Category[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const [form, setForm] = useState({
|
|
id: null as string | null,
|
|
name: "",
|
|
slug: "",
|
|
parentId: null as string | null,
|
|
});
|
|
|
|
async function load() {
|
|
setLoading(true);
|
|
try {
|
|
const [t, f] = await Promise.all([
|
|
getCategoriesTree(),
|
|
getCategoriesFlat(),
|
|
]);
|
|
|
|
setTree(t);
|
|
setFlat(f);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
load();
|
|
}, []);
|
|
|
|
async function save() {
|
|
const payload = {
|
|
name: form.name,
|
|
slug: form.slug || slugify(form.name),
|
|
parentId: form.parentId,
|
|
};
|
|
|
|
if (form.id) {
|
|
await updateCategory(form.id, payload);
|
|
} else {
|
|
await createCategory(payload);
|
|
}
|
|
|
|
resetForm();
|
|
load();
|
|
}
|
|
|
|
async function remove(id: string) {
|
|
await deleteCategory(id);
|
|
load();
|
|
}
|
|
|
|
function edit(cat: Category) {
|
|
setForm({
|
|
id: cat.id,
|
|
name: cat.name,
|
|
slug: cat.slug,
|
|
parentId: cat.parentId || null,
|
|
});
|
|
}
|
|
|
|
function resetForm() {
|
|
setForm({ id: null, name: "", slug: "", parentId: null });
|
|
}
|
|
|
|
return {
|
|
tree,
|
|
flat,
|
|
form,
|
|
setForm,
|
|
save,
|
|
remove,
|
|
edit,
|
|
resetForm,
|
|
loading,
|
|
};
|
|
} |