Below code is a method inside a class based component for react, in my opinion following code should work like this:
- first request will add data to both "data" and "one" variables.
- second request will add new field to each element inside "data" array.
So now "one" variable should only contains data from first request, but it will show new fields from second request too. what is happening here?
(I checked another tool like "superagent" too, but it has same behavior like axios)
loadData (id = undefined) {
// here i want to store real data for my app
let data = []
//
// this is a temporary variable which i used only to find out what is happening here
let one = []
//
// first axios request
axios.get('/loadContainers', {
headers: {
id: id
}
})
.then((res) => {
data = res.data.categories[0].categories
one = res.data.categories[0].categories
getData()
})
.catch((err) => {
console.log(err)
})
//
// second axios request
const getData = () => {
data.forEach((current, index) => {
axios.get('/relatedElements', {
headers: {
parentId: current.parentId
}
})
.then((res) => {
data[index].relatedElements = res.data.count[0].count
})
.catch((err) => {
console.log(err)
})
})
}
//
// print "one" variable when all the requests are done
setTimeout(() => {
console.log(one)
}, 8000)
//
}