I'm using react-hook-form with a watch to detect the a change in a <select> but after populating the select, the watch initially has the wrong value.
Here's some code to illustrate the problem:
import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";
function App() {
const { register, watch } = useForm();
const watchFoo = watch("foo");
const [foos, setFoos] = useState([]);
useEffect(() => {
setFoos([{ id: 1, name: "one" }, { id: 2, name: "two" }]);
}, []);
return (
<form>
<select {...register('foo')}>
{foos.map((foo, i) => (<option key={`option_${i}`} value={foo.id}>{foo.name}</option>))}
</select>
<p>foo is {watchFoo}</p>
</form>
);
}
export default App;
https://codesandbox.io/s/mystifying-kate-8n9xu
The useEffect simulates fetching the values from the server when the component is first loaded.
On first render, watchFoo has the value undefined as expected. After calling setFoos it renders again with the drop-down having the value "one" selected, but watchFoo has the value "". After changing the value in the drop-down, watchFoo is correct, but it's just the initial value that is wrong.
Is there any solution or workaround for this?
The "one" value hasn't actually had a selection event happen: it's just the first <option> in the list, so the rendered <select> shows it. The select element itself never had the events fire to update the internal form state with the new select box state. This causes a decoupling of the internal form state and the form state as represented in the page, because the browser will display the first option in the event that none of the options has the selected property (RFC 1866).
You can add an additional useEffect to update the hookform state when foos change:
const { register, watch, setValue } = useForm();
useEffect(() => {
if(watchFoo === "" && foos.length > 0) {
setValue("foo", foos[0].id);
}
}, [watchFoo, setValue, foos])
Another simpler option would be to just add an invisible blank option as your first entry:
<option style={{display: "none"}}></option>
This would result in your select showing a blank value by default, but without leaving the blank option as a selection option in your dropdown. This results in the form correctly reflecting the state of your internal form state, but wouldn't preselect the first option from the server. Select the technique which best fits your use case.