2022-01-19 14:28:55 +01:00
|
|
|
import { useEffect, useState } from 'react';
|
2022-03-28 10:49:59 +02:00
|
|
|
import useProjectApi from 'hooks/api/actions/useProjectApi/useProjectApi';
|
2022-06-07 15:03:40 +02:00
|
|
|
import { formatUnknownError } from 'utils/formatUnknownError';
|
2022-01-19 14:28:55 +01:00
|
|
|
|
|
|
|
const useProjectForm = (
|
|
|
|
initialProjectId = '',
|
|
|
|
initialProjectName = '',
|
|
|
|
initialProjectDesc = ''
|
|
|
|
) => {
|
|
|
|
const [projectId, setProjectId] = useState(initialProjectId);
|
|
|
|
const [projectName, setProjectName] = useState(initialProjectName);
|
|
|
|
const [projectDesc, setProjectDesc] = useState(initialProjectDesc);
|
|
|
|
const [errors, setErrors] = useState({});
|
|
|
|
const { validateId } = useProjectApi();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setProjectId(initialProjectId);
|
|
|
|
}, [initialProjectId]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setProjectName(initialProjectName);
|
|
|
|
}, [initialProjectName]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setProjectDesc(initialProjectDesc);
|
|
|
|
}, [initialProjectDesc]);
|
|
|
|
|
|
|
|
const getProjectPayload = () => {
|
|
|
|
return {
|
|
|
|
id: projectId,
|
|
|
|
name: projectName,
|
|
|
|
description: projectDesc,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-03-28 23:45:41 +02:00
|
|
|
const validateProjectId = async () => {
|
2022-01-25 12:30:55 +01:00
|
|
|
if (projectId.length === 0) {
|
|
|
|
setErrors(prev => ({ ...prev, id: 'Id can not be empty.' }));
|
|
|
|
return false;
|
|
|
|
}
|
2022-01-19 14:28:55 +01:00
|
|
|
try {
|
|
|
|
await validateId(getProjectPayload());
|
|
|
|
return true;
|
2022-06-07 15:03:40 +02:00
|
|
|
} catch (error: unknown) {
|
|
|
|
setErrors(prev => ({ ...prev, id: formatUnknownError(error) }));
|
2022-01-19 14:28:55 +01:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|
2022-02-18 08:26:26 +01:00
|
|
|
|
2022-01-19 14:28:55 +01:00
|
|
|
const validateName = () => {
|
|
|
|
if (projectName.length === 0) {
|
|
|
|
setErrors(prev => ({ ...prev, name: 'Name can not be empty.' }));
|
|
|
|
return false;
|
|
|
|
}
|
2022-01-25 12:30:55 +01:00
|
|
|
|
2022-01-19 14:28:55 +01:00
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
const clearErrors = () => {
|
|
|
|
setErrors({});
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
projectId,
|
|
|
|
projectName,
|
|
|
|
projectDesc,
|
|
|
|
setProjectId,
|
|
|
|
setProjectName,
|
|
|
|
setProjectDesc,
|
|
|
|
getProjectPayload,
|
|
|
|
validateName,
|
2022-01-25 00:47:49 +01:00
|
|
|
validateProjectId,
|
2022-01-19 14:28:55 +01:00
|
|
|
clearErrors,
|
|
|
|
errors,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useProjectForm;
|