Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Last active May 22, 2019 16:43
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 joemaffei/3745b92feafc96a974e5ca06075408e7 to your computer and use it in GitHub Desktop.
Save joemaffei/3745b92feafc96a974e5ca06075408e7 to your computer and use it in GitHub Desktop.
React hook for passive validation (e.g. on form submit)
import React, { useEffect, useState } from 'react';
function usePassiveValidation(value, validator) {
const [valid, setValid] = useState(true);
const [checkValue, setCheckValue] = useState(null);
const [didMount, setDidMount] = useState(false);
function validate() {
setCheckValue(value);
return validator(value);
}
useEffect(() => {
setDidMount(true);
}, []);
useEffect(() => {
setValid(true);
}, [value]);
useEffect(() => {
if (didMount) setValid(validator(checkValue));
}, [checkValue]);
return [ valid, validate ];
}
function Example() {
const [inputValue, setInputValue] = useState('');
const [validIfNotEmpty, validateInput] = usePassiveValidation(inputValue, x => !!x);
function handleChange(e) {
setInputValue(e.target.value);
}
return (
<div>
<input onChange={handleChange) value={inputValue} />
<br />
{validIfNotEmpty ? 'valid' : 'not valid'}
<br />
<button onClick={validateInput}>validate</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment