Skip to content

Instantly share code, notes, and snippets.

@honungsburk
Created March 2, 2023 09:19
Show Gist options
  • Save honungsburk/67de87842e9b6bc2515daa01fc8fe53b to your computer and use it in GitHub Desktop.
Save honungsburk/67de87842e9b6bc2515daa01fc8fe53b to your computer and use it in GitHub Desktop.
A react hook that provides helper functions and properties to use in a form input
import React from "react";
/**
* A hook that provides helper functions and properties to use in a form input
*
* @param initalValue - The initial value of the form input
* @param validate - A function that validates the value of the form input
* @returns an object with helper functions and properties to use in a form input
*
*/
function useFormControl<A>(
initalValue: A,
validate?: (value: A) => string | undefined
) {
const [value, setValue] = React.useState<A>(initalValue);
const [isDirty, setDirty] = React.useState<boolean>(false);
return {
value,
isDirty,
isInvalid: isDirty && validate?.(value) !== undefined,
error: validate?.(value),
setValue: (value: A) => {
setValue(value);
setDirty(true);
},
reset: () => {
setValue(initalValue);
setDirty(false);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment