Skip to content

Latest commit

 

History

History
56 lines (51 loc) · 2.43 KB

useMultiStateValidator.md

File metadata and controls

56 lines (51 loc) · 2.43 KB

useMultiStateValidator

Each time any of given states changes - validator function is invoked.

Usage

import { useMultiStateValidator, useState } from 'vue-next-use';

const DemoStateValidator = (s: number[]) => [s.every((num: number) => !(num % 2))] as [boolean];
const Demo = {
  setup(){
    const [state1, setState1] = useState<number>(1);
    const [state2, setState2] = useState<number>(1);
    const [state3, setState3] = useState<number>(1);
    const [[isValid]] = useMultiStateValidator([state1, state2, state3], DemoStateValidator);

    return () => (
            <div>
              <div>Below fields will be valid if all of them is even</div>
              <input type="number" min="1" max="10" value={state1}
                     onChange={(ev) => {
                       setState1((ev.target.value as unknown) as number);
                     }}
              />
              <input type="number" min="1" max="10" value={state2}
                     onChange={(ev) => {
                       setState2((ev.target.value as unknown) as number);
                     }}
              />
              <input type="number" min="1" max="10" value={state3}
                     onChange={(ev) => {
                       setState3((ev.target.value as unknown) as number);
                     }}
              />
              {isValid !== null && <span>{isValid ? 'Valid!' : 'Invalid'}</span>}
            </div>
    );
  }
};

Reference

const [validity, revalidate] = useStateValidator(
  state: any[] | { [p: string]: any } | { [p: number]: any },
  validator: (state, setValidity?)=>[boolean|null, ...any[]],
  initialValidity: any = [undefined]
);
  • state: any[] | { [p: string]: any } | { [p: number]: any } can be both an array or object. It's values will be used as a deps for inner useEffect.
  • validity: [boolean|null, ...any[]] result of validity check. First element is strictly nullable boolean, but others can contain arbitrary data;
  • revalidate: ()=>void runs validator once again
  • validator: (state, setValidity?)=>[boolean|null, ...any[]] should return an array suitable for validity state described above;
    • states - current states values as they've been passed to the hook;
    • setValidity - if defined hook will not trigger validity change automatically. Useful for async validators;
  • initialValidity - validity value which set when validity is nt calculated yet;