How To Fetch Multiple Api Request Or Url And Retrieve Data From Each Url Or Api Request?
In this method, I have fetched a single API Request URL function fetchData() { let url = 'http://127.0.0.1:8000/api/onlineUserData'; fetch(url) .then(response => respons
Solution 1:
Update your code to the following:
function fetchData(){
let urls = [
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'offline'
},
{
url: 'http://127.0.0.1:8000/api/offlineUserData',
type: 'offline'
},
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'online'
},
];
let requests = urls.map(item => fetch(item.url).then(response => response.json()));
const resultData = { offline: [], online: [] };
Promise.all(requests)
.then(datas => {
datas.forEach(
(data, i) => {
const url = urls[i];
if (url.type === 'offline')
resultData.offine.push({...url, data});
if (url.type === 'online')
resultData.online.push({...url, data});
});
console.log({resultData});
/*
{
resultData: {
offline: [
{
url: 'http://127.0.0.1:8000/api/oflineUserData',
type: 'offline',
data: [...]
},
{
url: 'http://127.0.0.1:8000/api/offlineUserData',
type: 'offline',
data: [...]
},
],
online: [
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'online',
data: [...]
},
]
}
}
*/
}
));
}
Post a Comment for "How To Fetch Multiple Api Request Or Url And Retrieve Data From Each Url Or Api Request?"