import { useCallback, useEffect, useState } from 'react'; import { useAuth } from '../Auth'; export default function useEntity(url?: any, id?: any, initialData?: any) { const [ api ] = useAuth(); const [ data, setData ] = useState(initialData || {}); const [ loading, setLoading ] = useState(false); const [ dirty, setDirty ] = useState(true); const applyData = useCallback(function(newData) { setDirty(true); setData(newData.apply ? newData : (data => ({ ...data, ...newData }))); }, [setData]); const update = useCallback(async function() { setLoading(true); try { const response = await api.tokenized.get(url + "/" + id); setData(response.data || initialData || {}); setDirty(false); } finally { setLoading(false); } }, [api, data, loading, url, id, initialData, setDirty]); const save = useCallback(async function() { setLoading(true); try { const response = await (id ? api.tokenized.patch(url + "/" + id, data) : api.tokenized.put(url, data)); setData(response.data); setDirty(false); return response.data; } finally { setLoading(false); } }, [api, data, loading, url, id, setDirty]); const saveAndSubmit = useCallback(async function(extraData) { setLoading(true); try { const response = await (id ? api.tokenized.patch(url + "/" + id, extraData ? {...data, ...extraData } : data) : api.tokenized.put(url, extraData ? {...data, ...extraData } : data)); setData(response.data); setDirty(false); return response.data; } finally { setLoading(false); } }, [api, data, loading, url, id, setDirty]); useEffect(function() { if (!data || data.id != id) { update(); } }, [url, id]); return [ data, applyData, save, loading, dirty, saveAndSubmit ]; }