I want to get json data from multiple url's and display it on frontend. Following are the url's:
1) localhost:3000/api/getdata1
2) localhost:3000/api/getdata2
3) localhost:3000/api/getdata3
Instead of using .fetch() on each of the url's like below:
.fetch('localhost:3000/api/getdata1')
.fetch('localhost:3000/api/getdata2')
.fetch('localhost:3000/api/getdata3')
I am going to make use of promise but how can I pass the search term of my search box as a query to my api endpoint ? Is there more efficient way or better way to do this (In ReactJS)-> Take search term from search box and then inject that search term inside api endpoint using template string feature of ES6.
const dataurls = [
'localhost:3000/api/getdata1/q={searchterm}',
'localhost:3000/api/getdata2/q={searchterm}',
'localhost:3000/api/getdata3/q={searchterm}'
];
const promisedurl = dataurls.map(httpGet);
Promise.all(promisedurls)
.then(data=> {
for (const d of data) {
console.log(d);
}
})
.catch(reason => {
// Receives first rejection among the Promises
});
You can use template literal
to add your searchterm
to your url.
const searchterm = 'abc'; const dataurls = [ `localhost:3000/api/getdata1/q=${searchterm}`, `localhost:3000/api/getdata2/q=${searchterm}`, `localhost:3000/api/getdata3/q=${searchterm}` ]; console.log(dataurls);
If i understand the problem correctly, one way of doing this could be
const dataUrls = [
'localhost:3000/api/getdata1',
'localhost:3000/api/getdata2',
'localhost:3000/api/getdata3'
];
const dataRequests = dataUrls.map((apiEndpoint) => fetch(`${apiEndpoint}/q=${searchTerm}`));
Promise.all(dataRequests)
.then((data) => {
for (const d of data) {
console.log(d);
}
})
.catch(reason => {
// Receives first rejection among the Promises
});
Although this is not specific to react
per say, this should get the job done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.