2

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')

Can this be done in more efficent way in ReactJs ?

I was trying:

const dataurls = [
    'localhost:3000/api/getdata1',
    'localhost:3000/api/getdata2',
    'localhost:3000/api/getdata3'
];
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
});

Please suggest which one should be used or is there any efficient way to do get data from multiple url's.

2
  • 1
    I would suggest you to make a new api that combines the data for all 3 requests and sends you the data. Commented Mar 3, 2018 at 8:16
  • @YashThakur Actually I want to query data from different API endpoints eg: localhost:3000/api/getdata3/search/query="searchterm" and display it. Commented Mar 10, 2018 at 12:22

1 Answer 1

2

ReactJS is a View layer library. It has nothing to do with how you aquire any data from server.

Even state libraries, like Redux and Reflux do not implement any method of fetching data. In most cases you do that in your custom app code. Sometimes using extra libraries (e.g. Redux middlewares).

So, yes: your Promise.all(<several https requests here>) is the most natural way to achieve that.

Sign up to request clarification or add additional context in comments.

6 Comments

I agree with this answer, and you can also cache the data returned by these requests to be more efficient.
@NícolasIensen How can I cache the data as I want to display data from different API endpoints by using search keyword eg: localhost:3000/api/getdata3/search/query="searchterm"
@stonerock There is no single answer on "how to cache". But the most trivial thing in your case is to use an object. Where key is url and value is response data (and then beware memory leaks).
@PavelKoryagin How can I overcome memory leak. I am totally new to this and I couldn't understand how there will be memory leakage.
@stonerock Ok, then I recommend you to forget about caching, until you'll face real performance issues. "Premature optimization is the root of all evil" (c) Donald Knuth. Focus on two things: features (what you do) and code layers (how you do, espesically on what View is, what Model is).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.