ConceptPortal-public/rsconcept/frontend/src/hooks/useRSFormDetails.ts

42 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-07-15 17:46:19 +03:00
import { useCallback, useEffect, useState } from 'react'
2023-07-25 20:27:29 +03:00
import { type ErrorInfo } from '../components/BackendError';
2023-07-20 17:11:03 +03:00
import { getRSFormDetails } from '../utils/backendAPI';
2023-07-25 20:27:29 +03:00
import { CalculateStats, type IRSForm } from '../utils/models'
2023-07-15 17:46:19 +03:00
2023-07-25 20:27:29 +03:00
export function useRSFormDetails({ target }: { target?: string }) {
const [schema, setInnerSchema] = useState<IRSForm | undefined>(undefined);
2023-07-15 17:46:19 +03:00
const [loading, setLoading] = useState(false);
const [error, setError] = useState<ErrorInfo>(undefined);
function setSchema(schema?: IRSForm) {
if (schema) CalculateStats(schema);
setInnerSchema(schema);
2023-07-25 22:29:33 +03:00
console.log('Loaded schema: ', schema);
}
const fetchData = useCallback(
2023-07-25 22:29:33 +03:00
async (setCustomLoading?: typeof setLoading) => {
2023-07-25 20:27:29 +03:00
setError(undefined);
if (!target) {
return;
}
await getRSFormDetails(target, {
showError: true,
2023-07-25 22:29:33 +03:00
setLoading: setCustomLoading ?? setLoading,
onError: error => { setInnerSchema(undefined); setError(error); },
2023-07-26 10:59:55 +03:00
onSuccess: (response) => { setSchema(response.data); }
2023-07-25 20:27:29 +03:00
});
}, [target]);
2023-07-15 17:46:19 +03:00
2023-07-25 22:29:33 +03:00
async function reload(setCustomLoading?: typeof setLoading) {
await fetchData(setCustomLoading);
2023-07-15 17:46:19 +03:00
}
useEffect(() => {
2023-07-25 20:27:29 +03:00
fetchData().catch((error) => { setError(error); });
2023-07-15 17:46:19 +03:00
}, [fetchData])
return { schema, setSchema, reload, error, setError, loading };
2023-07-25 20:27:29 +03:00
}