Using React hook form getValues() within useEffect return function, returns {}

Viewed 7763

I'm using react-hook-form library with a multi-step-form

I tried getValues() in useEffect to update a state while changing tab ( without submit ) and it returned {}

useEffect(() => {
    return () => {
      const values = getValues();
      setCount(values.count);
    };
  }, []);

It worked in next js dev, but returns {} in production

codesandbox Link : https://codesandbox.io/s/quirky-colden-tc5ft?file=/src/App.js

Details:

The form requirement is to switch between tabs and change different parameters and finally display results in a results tab. user can toggle between any tab and check back result tab anytime.

Implementation Example :

I used context provider and custom hook to wrap setting data state.

const SomeContext = createContext();

const useSome = () => {
  return useContext(SomeContext);
};

const SomeProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  const values = {
    setCount,
    count
  };

  return <SomeContext.Provider value={values}>{children}</SomeContext.Provider>;
};

Wrote form component like this ( each tab is a form ) and wrote the logic to update state upon componentWillUnmount.

as i found it working in next dev, i deployed it


const FormComponent = () => {
  const { count, setCount } = useSome();
  const { register, getValues } = useForm({
    defaultValues: { count }
  });

  useEffect(() => {
    return () => {
      const values = getValues(); // returns {} in production
      setCount(values.count);
    };
  }, []);

  return (
    <form>
      <input type="number" name={count} ref={register} />
    </form>
  );
};

const DisplayComponent = () => {
  const { count } = useSome();
  return <div>{count}</div>;
};

Finally a tab switching component & tab switch logic within ( simplified below )


const App = () => {
  const [edit, setEdit] = useState(true);

  return (
    <SomeProvider>
      <div
        onClick={() => {
          setEdit(!edit); 
        }}
      >
        Click to {edit ? "Display" : "Edit"}
      </div>
      {edit ? <FormComponent /> : <DisplayComponent />}
    </SomeProvider>
  );
}

0 Answers
Related