I am using ReactJS Autocomplete , where I get options from API . This seems working fine . Then I save data to DB using react-hook-form . On page load I get data using API and using SetValues I populate the form. But AutoComplete textInput don't show the value I received from API.
<Controller
render={(props, field) => (
<Autocomplete
// id="asynchronous-demo"
{...props}
open={open}
onOpen={() => {
setOpen(true)
}}
onClose={() => {
setOpen(false)
}}
filterOptions={(x) => x}
isOptionEqualToValue={(option, value) => {
setValue('city', option.city)
setValue('state', option.state)
return true
}}
getOptionLabel={
(option) => option.zipCode
}
renderOption={(props, option, { selected }) => (
<li {...props}>
{option.zipCode} City: {option.city} State:{' '}
{option.state}
</li>
)}
options={options}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
// value={getValues('zipCode')} // tried, but didn't worked
onKeyUp={(ev) => {
// dont fire API if the user delete or not entered anything
if (
ev.target.value !== '' ||
ev.target.value !== null
) {
onChangeHandle(ev.target.value)
}
}}
/>
)}
/>
)}
onChange={([, data]) => data}
defaultValue=getValues('zipCode') // tried, but didn't worked
/* defaultValue={ // tried, but didn't worked
fetchedData
? {
zipCode: getValues('zipCode'),
id: '',
city: '',
state: '',
}
: ''
} */
name="zipCode"
control={control}
/>
I have used defaultValues using object , using single value . and in textInput values also . But nothing worked for me.
I populate the options using below handler.
const onChangeHandle = async (value) => {
axios
.get(
`${process.env.REACT_APP_API_URL}/Settings/Searchcitystate?zipcode=${value}`,
{ headers }
)
.then((response) => {
// console.log('response.data: ', response.data)
const countries = response.data
setOptions(countries)
})
.catch((error) => {
console.error('There was an error!', error)
})
}