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

58 lines
1.6 KiB
TypeScript
Raw Normal View History

'use client';
import { useCallback, useEffect, useState } from 'react';
2023-07-25 20:27:29 +03:00
import { getRSFormDetails } from '@/backend/rsforms';
2024-03-20 15:27:32 +03:00
import { type ErrorData } from '@/components/info/InfoError';
import { useAuth } from '@/context/AuthContext';
import { IRSForm, IRSFormData } from '@/models/rsform';
import { RSFormLoader } from '@/models/RSFormLoader';
2023-07-15 17:46:19 +03:00
2024-03-04 19:22:22 +03:00
function useRSFormDetails({ target, version }: { target?: string; version?: string }) {
const { loading: userLoading } = useAuth();
const [schema, setInnerSchema] = useState<IRSForm | undefined>(undefined);
2024-07-19 20:43:09 +03:00
const [loading, setLoading] = useState(target != undefined);
const [error, setError] = useState<ErrorData>(undefined);
2023-07-15 17:46:19 +03:00
function setSchema(data?: IRSFormData) {
if (!data) {
setInnerSchema(undefined);
return;
}
const schema = new RSFormLoader(data).produceRSForm();
setInnerSchema(schema);
}
const reload = useCallback(
2023-12-28 14:04:44 +03:00
(setCustomLoading?: typeof setLoading, callback?: () => void) => {
setError(undefined);
if (!target) {
return;
2023-07-25 20:27:29 +03:00
}
2024-03-04 19:22:22 +03:00
getRSFormDetails(target, version ?? '', {
2023-12-28 14:04:44 +03:00
showError: true,
setLoading: setCustomLoading ?? setLoading,
onError: error => {
setInnerSchema(undefined);
setError(error);
},
onSuccess: schema => {
setSchema(schema);
if (callback) callback();
}
});
},
2024-03-04 19:22:22 +03:00
[target, version]
2023-12-28 14:04:44 +03:00
);
2023-07-15 17:46:19 +03:00
useEffect(() => {
if (!userLoading) {
reload();
}
}, [reload, userLoading]);
2023-07-15 17:46:19 +03:00
return { schema, setSchema, reload, error, setError, loading };
2023-07-25 20:27:29 +03:00
}
2023-12-28 14:04:44 +03:00
export default useRSFormDetails;