'Is this the wrong way of handling array of objects from api call?
I am trying to store a array of names from a json response containing an array of objects.
For some reason the printing array will have nothing inside.Is this the correct way of doing it. Its not working for some reason otherwise no errors.
also the forEach is loop not even running once i tested it.
useEffect(() => {
instance.get('/')
.then(function (response) {
// handle success
//console.log(response);
console.log(response.data);
(response.data).forEach(newValue=>
{
setArray(oldArray => [...oldArray,newValue.name])
}
)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
console.log("printing array 1",Array);
// always executed
});
if(Array)
console.log("printing array 2",Array);
},[]);
Solution 1:[1]
Try this:
setArray([...oldArray, ...response.data?.map(item=>item.name)]);
Rather than updating your state for every item in the new array, just get all the name props as an array from the new array using map and then use the spread operator to combine both new and old arrays.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ogheneochuko Pedro |
