Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

reactjs - Fetch API requesting multiple get requests

I would like to know how to fetch multiple GET URLs at once and then put the fetched JSON data into my React DOM element.

Here is my code:

fetch("http://localhost:3000/items/get")
.then(function(response){
        response.json().then(
            function(data){
                ReactDOM.render(
                    <Test items={data}/>,
                    document.getElementById('overview')
                );}
        );
    })
.catch(function(err){console.log(err);});

However, I would like to fetch additional JSON datas from my server and then render my ReactDOM with all these JSON datas passed into it. For example:

ReactDOM.render(
   <Test items={data} contactlist={data2} itemgroup={data3}/>,
   document.getElementById('overview')
);

Is this possible? If not, what are other solutions to fetching multiple JSON data into my rendering ReactDOM element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can rely on Promises to execute them all before your then resolution. If you are used to jQuery, you can use jQuery Promises as well.

With Promise.all you will enforce that every request is completed before continue with your code execution

Promise.all([
  fetch("http://localhost:3000/items/get"),
  fetch("http://localhost:3000/contactlist/get"),
  fetch("http://localhost:3000/itemgroup/get")
]).then(([items, contactlist, itemgroup]) => {
    ReactDOM.render(
        <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
        document.getElementById('overview');
    );
}).catch((err) => {
    console.log(err);
});

But even tough, fetch is not implemented in all browsers as of today, so I strongly recommend you to create an additional layer to handle the requests, there you can call the fetch or use a fallback otherwise, let's say XmlHttpRequest or jQuery ajax.

Besides of that, I strongly recommend you to take a look to Redux to handle the data flow on the React Containers. Will be more complicated to setup but will pay off in the future.

Update August 2018 with async/await

As of today, fetch is now implemented in all the latest version of the major browsers, with the exception of IE11, a wrapper could still be useful unless you use a polyfill for it.

Then, taking advantage of newer and now more stable javascript features like destructuring and async/await, you might be able to use a similar solution to the same problem (see the code below).

I believe that even though at first sight may seem a little more code, is actually a cleaner approach. Hope it helps.

try {
  let [items, contactlist, itemgroup] = await Promise.all([
    fetch("http://localhost:3000/items/get"),
    fetch("http://localhost:3000/contactlist/get"),
    fetch("http://localhost:3000/itemgroup/get")
  ]);

  ReactDOM.render(
    <Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
      document.getElementById('overview');
  );
}
catch(err) {
  console.log(err);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...