I am new to React.
The for loop is used to fetch data from the url with different ids.
The object from data contains same keys and different values.
What I want to do is I want to store these data objects into array with index.
Looking like the following:
dataArr [
0: {key: 1, value: 1},
1: {key: 2, value: 2},
2: {key: 3, value: 3}
]
Here is what I have tried.
var ids = [1,2,3]
const [data, setData] = useSate({});
const dataArr = [];
const fetchData = async() => {
for(var i =0; i < ids.length; i++) {
axios.get(`http://myURL/${ids[i]}`)
.then(res => {
dataArr.push(setData(res.data))
})
}
}
useEffect(() => {
fetchData ();
},[]);
console.log(dataArr[0]) //undefined
console.log(dataArr) // empty
console.log(data) // get objects independently
Can anybody advise me?