Reggie Snow
Reggie Snow

Reputation: 152

loading Multiple URLS using fetch in React

I am attempting to fetch multiple URLs in React using the Promise.all() method:

const urls = [
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=2",
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=3",
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=4"
];

Promise.all(urls.map(url => fetch(url).then(res => res.json()))).then(
  members => {
    console.log(members);
    this.setState({
      nearbymems: members.members
    });
  }
);

The console.log is returning all of the URLs together but it is not displaying them on my map application. I have declared an empty array in my state : nearbymems: []

I will also post my render() function for displaying the data as markers in leaflet:

{this.state.nearbymems.map(members => (
  <Marker
    position={[members.location.latitude, members.location.longitude]}
    icon={myIcon1}
  >
    <Popup>
      <h1 className="lead">{members.name} </h1>

      <PopupModal initialModalState={true} />
    </Popup>
  </Marker>
))}

Thank you.

edit:

Output of array:

 (3) [{…}, {…}, {…}]
 0:
   format:"json"
   latlon:"53,-6"
   members: Array(50)
   0:
      bio:" "
      date:""
      id:44967
      location:
         {latitude: "53.31138992", longitude: "-6.24345493"}
      name: "______"
      url:"https://thesession.org/members/___"
 __proto__: Object

Upvotes: 2

Views: 5653

Answers (2)

Tholle
Tholle

Reputation: 112887

You want to take the members array from each fetch response, and then concatenate these arrays into one before you put it as nearbymems in state.

Promise.all(
  urls.map(url =>
    fetch(url)
      .then(res => res.json())
      .then(res => res.members)
  )
).then(members => {
  this.setState({
    nearbymems: [].concat(...members)
  });
});

Upvotes: 2

Seth
Seth

Reputation: 10454

Promise.all returns an array with each item containing the resolved value of its respective promise. Therefore you cannot simply access members from the result of Promise.all. Instead you must merge all the values together to get one large array of each promise's members value.

This will return all members from each request into a single flattened array.

const urls = [
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=2",
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=3",
  "https://thesession.org/members/nearby?latlon=53,-6&radius=1000&format=json&perpage=50&page=4"
];
const requests = urls.map(url => fetch(url).then(res => res.json()));
const toMembers = responses => responses.map(response => response.members);

Promise.all(requests).then(toMembers).then(members => console.log(members.flat()));

Upvotes: 1

Related Questions