Skip to content

Instantly share code, notes, and snippets.

@lxsmnsyc
Last active August 3, 2020 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lxsmnsyc/627a83d47e67dc63364ba9dcc6f95160 to your computer and use it in GitHub Desktop.
Save lxsmnsyc/627a83d47e67dc63364ba9dcc6f95160 to your computer and use it in GitHub Desktop.
export default function useValidState(validator, initialState) {
const [state, setState] = useState(initialState);
const [error, setError] = useState();
const set = useCallback((action) => {
setState((prev) => {
const value = typeof action === 'function'
? action(prev)
: action;
try {
return validator.validateSync(value);
} catch (err) {
setError(err);
return prev;
}
});
}, [validator]);
return [{ state, error }, set];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment