1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/frontend/src/component/segments/hooks/useSegmentForm.ts
Nuno Góis fe1e3566ee
fix: assume undefined instead of null on segment project (#3304)
Assume `undefined` instead of `null` for project in terms of interfacing
with segments: If the `project` field is not present, that means that it
is not set, which means we're dealing with a "global" segment. If we
want to unset `project` and make a segment global, we simply don't send
the `project` property on our PUT method.
2023-03-13 10:25:48 +00:00

70 lines
1.7 KiB
TypeScript

import { IConstraint } from 'interfaces/strategy';
import { useEffect, useState } from 'react';
import { useSegmentValidation } from 'hooks/api/getters/useSegmentValidation/useSegmentValidation';
export const useSegmentForm = (
initialName = '',
initialDescription = '',
initialProject?: string,
initialConstraints: IConstraint[] = []
) => {
const [name, setName] = useState(initialName);
const [description, setDescription] = useState(initialDescription);
const [project, setProject] = useState<string | undefined>(initialProject);
const [constraints, setConstraints] =
useState<IConstraint[]>(initialConstraints);
const [errors, setErrors] = useState({});
const nameError = useSegmentValidation(name, initialName);
useEffect(() => {
setName(initialName);
}, [initialName]);
useEffect(() => {
setDescription(initialDescription);
}, [initialDescription]);
useEffect(() => {
setProject(initialProject);
}, [initialProject]);
useEffect(() => {
setConstraints(initialConstraints);
// eslint-disable-next-line
}, [JSON.stringify(initialConstraints)]);
useEffect(() => {
setErrors(errors => ({
...errors,
name: nameError,
}));
}, [nameError]);
const getSegmentPayload = () => {
return {
name,
description,
project,
constraints,
};
};
const clearErrors = () => {
setErrors({});
};
return {
name,
setName,
description,
setDescription,
project,
setProject,
constraints,
setConstraints,
getSegmentPayload,
clearErrors,
errors,
};
};