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);
},[]);
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.