Reputation: 59
I wanted to use Axios get to put the contents value of 'card' and call the data and put the value in 'wordAll', but it failed. I want to combine and store the arrays I received as an axios in the state through the map function. Sometimes the code I wrote comes in and sometimes it doesn't. I know my code is wrong.
Please teach me the way.
const [wordAll, setWordAll] = useState([]);
useEffect(() => {
cards.map((contents) => {
axios
.get(`https/api/words/detail_list/?contents=${contents.contents}`, {
headers: {
Authorization: cookies.token,
},
})
.then((res) => {
let indata = res.data;
for (var i = 0; i < indata.length; i++) {
wordAll.push(indata[i]);
setWordAll(wordAll);
}
console.log('wordAll0', wordAll);
})
.catch((error) => {
console.log('err==>', error);
});
});
}, []);
console.log('wordAll1', wordAll);
Upvotes: 0
Views: 84
Reputation: 1568
You can keep the cards axios request promises in an array (cardsPromises
) and then use Promise.all
to get the values from the resolved promises.
useEffect(() => {
const cardsPromises = cards.map((contents) =>
axios.get(`https/api/words/detail_list/?contents=${contents.contents}`, {
headers: {
Authorization: cookies.token
}
})
);
Promise.all(cardsPromises)
.then((resp) => {
//resp will be an array of resolved values
setWordAll(resp);
})
.catch((error) => {
console.log("err==>", error);
});
}, []);
Upvotes: 1