When you are working with users' input, things will get tricky.
useState
does not validate your data correctly, it is unsafe. useStateValidation
instead gives you access to the user input only if the format is valid.
This hook uses fp-ts
and functional programming, specifically the Either
type. You need to provide both an initial value (just like a normal useState
hook) as well as a validation function. The validation function returns Right
when the input data is valid, and Left
otherwise.
By using this hook, you guarantee that your data is always valid.
import * as E from "fp-ts/Either";
import { Dispatch, SetStateAction, useState } from "react";
export const useStateValidation = <InputValue, ValidValue, ErrorType>(
initialValue: InputValue,
validate: (i: InputValue) => E.Either<ErrorType, ValidValue>
): [
InputValue,
Dispatch<SetStateAction<InputValue>>,
E.Either<ErrorType, ValidValue>,
boolean,
() => void
] => {
const [isDirty, setIsDirty] = useState<boolean>(false);
const [value, setValue] = useState<InputValue>(initialValue);
const setValueDirty: Dispatch<SetStateAction<InputValue>> = (v) => {
setIsDirty(true);
setValue(v);
};
const reset = () => {
setIsDirty(false);
setValue(initialValue);
};
return [value, setValueDirty, validate(value), isDirty, reset];
};