You should be able to simplify this so that you're not calling setListRealm multiple times: setListItems(lstR => [. lstR, . resp.data.map(res => (< value: res.id, label: res.name>))]) , as a side note .map() for iteration only is not what map should be used for, instead .forEach() can be used
Commented Nov 5, 2021 at 10:34The name you use in the setListRealm callback can be anything you want, so you can just make it previousListRealm or just previous or something:
setListRealm(previousListRealm => [. previousListRealm, < value: res.id, label: res.name>]);
It doesn't have to match the name of the constant you've put the value from useState in.
A few other suggestions:
useEffect(() => < const findList = async () => < const < data >= await axios.get(apiUrl); const additions = data.map((< id, name >) => (< value: id, label: name >)); setListRealm((previous) => [. previous, . additions]); >; findList() .catch((error) => < // . handle.report error. >); >, []);
Or don't use an extra function at all:
useEffect(() => < axios.get(apiUrl) .then(() => < const additions = data.map((< id, name >) => (< value: id, label: name >)); setListRealm((previous) => [. previous, . additions]); >) .catch((error) => < // . handle.report error. >); >, []);