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 }) {
|
2023-07-24 22:34:03 +03:00
|
|
|
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);
|
|
|
|
|
2023-07-24 22:34:03 +03:00
|
|
|
function setSchema(schema?: IRSForm) {
|
|
|
|
if (schema) CalculateStats(schema);
|
|
|
|
setInnerSchema(schema);
|
2023-07-25 22:29:33 +03:00
|
|
|
console.log('Loaded schema: ', schema);
|
2023-07-24 22:34:03 +03:00
|
|
|
}
|
|
|
|
|
2023-07-23 21:38:04 +03:00
|
|
|
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])
|
|
|
|
|
2023-07-24 22:34:03 +03:00
|
|
|
return { schema, setSchema, reload, error, setError, loading };
|
2023-07-25 20:27:29 +03:00
|
|
|
}
|