I have multiple api's that are returning same type of data but from different areas but the data type is the same only the values are different, and I want to store them all in one react state.
So I have this state:
let [infoData1, setInfoData1] = useState({ infoData1: [] });
let [infoData2, setInfoData2] = useState({ infoData2: [] });
and the axios calls :
function multipleApiCall() {
const headers = {
"X-Api-Key": "the-api-key-00",
};
axios.get(
"http:url-to-data/ID1",
{ headers }
)
.then((response) => {
setInfoData1(response.data);
return axios.get(
"http:url-to-data/ID2",
{ headers }
)
})
.then(response => {
setInfoData2(response.data);
})
}
and afterward I want to use a .map()
to list the result but because I have 2 states I cannot concatenate them. So how can I have all data from those two api's in just one state or maybe another approach ?
CodePudding user response:
const [infoData, setInfoData] = useState([]);
const headers = {
"X-Api-Key": "the-api-key-00",
};
const urls = ["http:url-to-data/ID1", "http:url-to-data/ID2"];
function multipleApiCall() {
const promises = urls.map(url => axios.get(url, { headers }));
Promise.all(promises).then(responses => {
let data = [];
responses.forEach(response => {
data = data.concat(response.data);
});
setInfoData(data);
});
}