Issue
I'm calling a api with another api like
First api have list like a labels:-
{
"body": [
{
"label": "label one",
"inputVal": "input value one"
},
{
"label": "label two",
"inputVal": "input value two"
}
]
}
Second api will validate each label and input as we are using in first api:- so I'm calling second api two time (it may be more than two) because I need to validate two label and input as in first api.
const [inputVal, setInputVal] = useState([]);
async function firstApi() {
axios
.post('first_api_url', {
title: "title",
})
.then((res) => {
if (res) {
res.data.body.forEach((val) => {
secondApi();
});
}
});
}
async function secondApi() {
axios
.post('second_api_url', {
titleSecondApi: "titleSecondApi",
})
.then((res) => {
if (res.data.body.msg) {
setInputVal([res.data.body.msg]);
console.log(inputVal);
}
});
}
Now I'm getting second api response only last response but I need all response in an array.
I'm using inputVal useState for that but not getting all the values in array how to get it?
Thanks for your efrorts!
Solution
If I got your point correctly, you may try to change your code like that:
const [inputVal, setInputVal] = useState([]);
async function firstApi() {
axios
.post('first_api_url', {
title: "title",
})
.then((res) => {
if (res) {
res.data.body.forEach((val) => {
secondApi();
});
}
});
}
async function secondApi() {
axios
.post('second_api_url', {
titleSecondApi: "titleSecondApi",
})
.then((res) => {
if (res.data.body.msg) {
setInputVal(prev=> {
return [...prev, res.data.body.msg]
});
console.log(inputVal);
}
});
}
Answered By - mikenlanggio
Answer Checked By - - Pedro (ReactFix Volunteer)