2022-03-29 09:30:57 +02:00
|
|
|
import { IConstraint } from 'interfaces/strategy';
|
|
|
|
import { useEffect, useState } from 'react';
|
2022-04-08 12:34:59 +02:00
|
|
|
import { useSegmentValidation } from 'hooks/api/getters/useSegmentValidation/useSegmentValidation';
|
2022-03-29 09:30:57 +02:00
|
|
|
|
|
|
|
export const useSegmentForm = (
|
|
|
|
initialName = '',
|
|
|
|
initialDescription = '',
|
2023-03-10 09:16:54 +01:00
|
|
|
initialProject: string | null = null,
|
2022-03-29 09:30:57 +02:00
|
|
|
initialConstraints: IConstraint[] = []
|
|
|
|
) => {
|
|
|
|
const [name, setName] = useState(initialName);
|
|
|
|
const [description, setDescription] = useState(initialDescription);
|
2023-03-10 09:16:54 +01:00
|
|
|
const [project, setProject] = useState<string | null>(initialProject);
|
2022-03-29 09:30:57 +02:00
|
|
|
const [constraints, setConstraints] =
|
|
|
|
useState<IConstraint[]>(initialConstraints);
|
|
|
|
const [errors, setErrors] = useState({});
|
2022-04-08 12:34:59 +02:00
|
|
|
const nameError = useSegmentValidation(name, initialName);
|
2022-03-29 09:30:57 +02:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setName(initialName);
|
|
|
|
}, [initialName]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setDescription(initialDescription);
|
|
|
|
}, [initialDescription]);
|
|
|
|
|
2023-03-10 09:16:54 +01:00
|
|
|
useEffect(() => {
|
|
|
|
setProject(initialProject);
|
|
|
|
}, [initialProject]);
|
|
|
|
|
2022-03-29 09:30:57 +02:00
|
|
|
useEffect(() => {
|
|
|
|
setConstraints(initialConstraints);
|
|
|
|
// eslint-disable-next-line
|
|
|
|
}, [JSON.stringify(initialConstraints)]);
|
|
|
|
|
2022-04-08 12:34:59 +02:00
|
|
|
useEffect(() => {
|
|
|
|
setErrors(errors => ({
|
|
|
|
...errors,
|
|
|
|
name: nameError,
|
|
|
|
}));
|
|
|
|
}, [nameError]);
|
|
|
|
|
2022-03-29 09:30:57 +02:00
|
|
|
const getSegmentPayload = () => {
|
|
|
|
return {
|
|
|
|
name,
|
|
|
|
description,
|
2023-03-10 09:16:54 +01:00
|
|
|
project,
|
2022-03-29 09:30:57 +02:00
|
|
|
constraints,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const clearErrors = () => {
|
|
|
|
setErrors({});
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
name,
|
|
|
|
setName,
|
|
|
|
description,
|
|
|
|
setDescription,
|
2023-03-10 09:16:54 +01:00
|
|
|
project,
|
|
|
|
setProject,
|
2022-03-29 09:30:57 +02:00
|
|
|
constraints,
|
|
|
|
setConstraints,
|
|
|
|
getSegmentPayload,
|
|
|
|
clearErrors,
|
|
|
|
errors,
|
|
|
|
};
|
|
|
|
};
|