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

48 lines
1.3 KiB
TypeScript
Raw Normal View History

import { useCallback, useEffect, useState } from 'react';
2023-07-25 20:27:29 +03:00
import { type ErrorInfo } from '../components/BackendError';
import { IRSForm, IRSFormData } from '../models/rsform';
import { loadRSFormData } from '../models/rsformAPI';
2023-07-20 17:11:03 +03:00
import { getRSFormDetails } from '../utils/backendAPI';
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(data?: IRSFormData) {
if (!data) {
setInnerSchema(undefined);
return;
}
2023-09-11 20:31:54 +03:00
const schema = loadRSFormData(data);
setInnerSchema(schema);
}
const reload = useCallback(
2023-11-04 01:29:21 +03:00
(setCustomLoading?: typeof setLoading, callback?: () => void) => {
setError(undefined);
if (!target) {
return;
}
getRSFormDetails(target, {
showError: true,
setLoading: setCustomLoading ?? setLoading,
onError: error => {
setInnerSchema(undefined);
setError(error);
},
onSuccess: schema => {
setSchema(schema);
if (callback) callback();
2023-07-25 20:27:29 +03:00
}
2023-11-04 01:29:21 +03:00
});
}, [target]);
2023-07-15 17:46:19 +03:00
useEffect(() => {
reload();
}, [reload])
2023-07-15 17:46:19 +03:00
return { schema, setSchema, reload, error, setError, loading };
2023-07-25 20:27:29 +03:00
}