Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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