Reputation: 1251
Code SandBox Here https://codesandbox.io/s/wild-brook-jpeio?file=/src/App.js
I acquire an array of values using useEffect hook. The array variable is set using useState hook
The value and onChange attributes of Native Select also uses another state variable and its set function to update it.
Using the below part of code to use the set function to set the selected value of the Native Select just after the useEffect gets the data.
// set the default selection on first load
if (!isEmpty(combolist)) {
console.log(combolist[0].name);
setSelection(combolist[0].name);
}
But this is giving too many renders error.
How to fix this and achieve my objective
Upvotes: 0
Views: 642
Reputation: 6582
you need to use a useEffect
hook for that like this:
useEffect(() => {
if (data.length) {
const combolist = data.map((obj) => pick(obj, ["id", "name"]));
// set the default selection on first load
if (!isEmpty(combolist)) {
console.log(combolist[0].name);
setSelection(combolist[0].name);
}
}
}, [data]);
Upvotes: 1
Reputation: 2523
One easy way is move the set the combolist
in useEffect
to prevent the multiple re-render.
This is the solution link.
Upvotes: 1