I am using react-select dropdown with react-hook-form library. I am calling an api to get defaultValue for react-select. Initially dropdown was not able to prepopulate the defaultValue. So i found a workaround for that and re render the whole JSX when i get data from api.
<form onSubmit={handleSubmit(saveData)}>
{!countryValue && (
<Controller
name="country"
control={control}
render={({ onChange, value, ref }) => (
<Select
options={country}
value={country.find((c) => c.value === value)}
onChange={(val) => onChange(val.value)}
/>
)}
rules={{ required: true }}
/>
)}
{countryValue && (
<Controller
name="country"
control={control}
render={({ onChange, value, ref }) => (
<Select
options={country}
value={country.find((c) => c.value === value)}
onChange={(val) => onChange(val.value)}
defaultValue={country.find((c) => c.value === countryValue)}
/>
)}
rules={{ required: true }}
/>
)}
{errors.country && <div>Field is rquired</div>}
<button type="submit">Save</button>
</form>
I put a condition on countryValue that when component get the value of countryValue it render the whole dropdown.
But when i submit the form with the same defaultValue hook form gives an error of country field as undefined.
I have created a sandbox for this. https://codesandbox.io/s/react-select-with-react-hook-form-sc2xz
How can solve this issue. Is their any workaround.