I have a react select component I want to update data so when I fetch data from my API i want to set my data to react select I use this code.
I have create state and use useEffect to fetch data from an API
const [currency, setCurrency] = useState([]);
useEffect(() => {
if (sessionStorage.getItem('AccountId')) {
axios.get(process.env.REACT_APP_SQL_API_URL + 'Organisation/' + query.search.split('=')[1])
.then(res => {
setCurrency({ label: res.data[0].currency, value: res.data[0].currency });
})
.catch(error => console.log(error.response))
}
else {
history.push('/login')
}
}, [])
This is the react select code
<Controller
rules={{ required: true }}
name="currency"
control={control}
render={({ field: { onChange } }) =>
<Select
onChange={(e) => {
onChange(e)
//handleSelect(e)
}}
options={[{ value: 'USD', label: 'USD $' }, { value: 'TZS', label: 'TZS' }]}
defaultValue={[currency]}
/>
}
/>
you need to have a state :
const [currency, setCurrency] = useState([]);
<Controller
rules={{
required: true }}
name="currency"
control={control}
render={({ field: { onChange } }) =>
<Select
onChange={(e) => {
onChange(e)
//handleSelect(e)
console.log(e.target);
console.log(e.target.value);
setCurrency(state=>[ //change state ])
}}
options={[{ value: 'USD', label: 'USD $' }, { value: 'TZS', label: 'TZS' }]}
defaultValue={currency}
value={currency}
/>
}
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.