File size: 2,404 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React from 'react';
import { useForm, useWatch } from 'react-hook-form';

function useInputCache(values, causeField, effectField, callback) {
  const [effectCache, setEffectCache] = React.useState(values[effectField]);

  const evaluateRegStatus = (vals, currentState) => {
    // check if field is registered (naive implementation for demonstration)
    const isRegistered = !!vals[causeField];
    return {
      isRegistered,
      registrationStatusChanged: isRegistered !== currentState,
      hasValue: vals[effectField] !== undefined,
    };
  };

  // use ref to track registration state across renders
  const currentRegState = React.useRef(false);

  React.useEffect(() => {
    const { isRegistered, registrationStatusChanged, hasValue } =
      evaluateRegStatus(values, currentRegState.current);

    if (registrationStatusChanged && hasValue) {
      if (isRegistered && !!effectCache) {
        console.debug('Deploying cache');
        callback(effectField, effectCache);
      } else if (!isRegistered) {
        console.debug('Caching before unmount');
        setEffectCache(values[effectField]);
      }
      currentRegState.current = !!isRegistered;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [values, causeField, effectField, callback]);
}

export default function App() {
  const { register, handleSubmit, setValue, control } = useForm({
    mode: 'onChange',
    defaultValues: {
      name: '',
      check: false,
      optionalText: '',
    },
  });

  const values = useWatch({
    control,
  });
  useInputCache(values, 'check', 'optionalText', setValue);

  return (
    <div className="App">
      <h1>Here's a form with conditional fields.</h1>
      <form onSubmit={handleSubmit(console.log)}>
        <input
          name={'name'}
          type={'text'}
          ref={register({ required: true, min: 3 })}
          placeholder={'Enter a name'}
        />
        <br />
        <label htmlFor={'check'}>
          toggle field:
          <input
            name={'check'}
            type={'checkbox'}
            ref={register({ required: true })}
          />
        </label>
        <br />
        {values.check && (
          <input
            name={'optionalText'}
            ref={register({ required: false })}
            placeholder={'Mandatory when check=true'}
          />
        )}
      </form>
    </div>
  );
}