my problem is about nested axios request. The code is very simple, with first axios.get i am fetching first portion of data and then using the given respons I am trying to fetch data from second endpoint. (code below)
const getData = async () => {
let returnSecoundValue = {}
try {
const response = await axios.get("http://127.0.0.1:8000/firstEndpoint/", {
auth: {
username: "x",
password: "y",
},
});
// console.log(response.data) <--- WORKS;
response.data.forEach(async element => {
const secoundData = await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`, {
auth: {
username: "x",
password: "y",
},
});
returnSecoundValue[secoundData.data.id] = secoundData.data
});
console.log(returnSecoundValue) <--- WORKS;
setMyState({firstEnd: response.data, secoundEnd: empoRet})
} catch (err) {
console.error(err);
}
As in example above when I am finished fetching second data, I save it in my state as an object. The First element of an object is an array of objects, and the second is the object (used as disc).
Up to this point everything is fine, when I try and console.log it, it shows perfectly as I wanted. Problem starts when I'am trying to get the exact data from the second element.
With my fetched data I'am trying to do something like that:
myState.firstEnd.map((element) => {
try{
console.log(myState); (Works - log all values)
console.log(myState.secoundEnd); (Works - log all values of secoundEnd)
console.log(myState.secoundEnd[2]); (Return undefind)
<Component
key={element.id}
isActive={element.active}
title={element.title}
I have tried to do that in few approaches but each time I ended up with the same result. Is there a problem with mounting or is it something else?
Thanks to the comments, I figured out the problem. This is the solution:
const secoundValue = response.data.map(async element => {
await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`,
{
auth: {
username: "x",
password: "y",
},
});
});
Promise.all(secoundValue).then((res) => {
res.map((e)=>{
secoundEnd[e.data.id] = e.data
})
setMyState({ ads: resp.data, emp: empoRet });
});