Last active
August 3, 2020 10:17
-
-
Save lxsmnsyc/627a83d47e67dc63364ba9dcc6f95160 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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