Skip to content

tech

Form data validation hook with fp-ts and functional programming

React hook used to store, update, and validate data using functional programming with fp-ts.


Software
1 min read

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.

useStateValidation.ts
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];
};

Continue the thread every Wednesday

One focused idea about type-safe software, AI-assisted development, and creative practice.

Free, no spam, unsubscribe anytime. See the privacy policy.

Want to see what arrives? Explore the newsletter