import { useState, } from 'react'; import CategoryService from "../services/CategoryService"; export function useCategories() { const [categories, setCategories] = useState(null); async function getCategories() { try { const response = await CategoryService.getAll(); setCategories(response); } catch (error) { console.log(error); } } async function getCategoryById(id) { try { if (!categories || categories.length == 0) { const response = await CategoryService.getById(id); setCategories([response]); return response; } const c = categories.find(category => category.id == id); if (c) { return c; } else { const response = await CategoryService.getById(id); setCategories([...categories, response]); return response; } } catch (error) { console.log(error); return {}; } } return { categories, getCategories, getCategoryById }; }