Home > database >  how to fetch multiple api's with promise.all?
how to fetch multiple api's with promise.all?

Time:10-18

I've been messing around with this coding challenge but now I've come up a bit stuck. I'm not sure if I understand the challenge.

This is the challenge Your goal is to create a page showing a list of hotels and their rooms.

query the following API:

https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG

This returns a list of hotels, with an Id. The Id can be used to query this query for the room types:

https://obmng.dbm.guestline.net/api/roomRates/OBMNG/[hotelId] for example, https://obmng.dbm.guestline.net/api/roomRates/OBMNG/OBMNG1

how would i go about this ? I read something about Promise.all - is that what I would need here ?

I have something like this but not sure on the next step

async componentDidMount () {

const url = "https://obmng.dbm.guestline.net/api/roomRates/OBMNG/OBMNG1";
const urlSecond = "https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG";
const response = await fetch(url);
const response = await fetch (urlSecond);
const data = await  response.json();
const data = await response.json();
this.setState({hotel:data.rooms[0], loading: false});
this.setState({hotel:data, loading:false});
console.log(data.rooms[0]);
console.log(data);

Let me know what I should be doing - thank you

CodePudding user response:

What you want to do is first fetch the hotels, and then for each hotel send a request for the rooms information. You'll see that we will end up with a final array of objects. Each index in the array will have a hotel key with the hotels information, and then a rooms key with all of the rooms information for that hotel.

Here is a working codesandbox.

import { useEffect, useState } from 'react'

export default function App() {
  const [hotelRooms, setHotelRooms] = useState([])

  const fetchHotels = async () => {
    const res = await fetch('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
    const hotels = await res.json()
    
    const hotelRooms = []

    for(const hotel of hotels) {
      const res = await fetch(`https://obmng.dbm.guestline.net/api/roomRates/OBMNG/${hotel.id}`)
      const info = await res.json()
      hotelRooms.push({ hotel, rooms: info.rooms })
    }

    setHotelRooms(hotelRooms)
  }

  useEffect(() => {
    fetchHotels()
  }, [])

  return (
    <div className="App">
      {
        hotelRooms.map(h => (
          <div>
            <h2>{h.hotel.name}</h2>
            <p>{h.hotel.description}</p>

            <p style={{ fontWeight: 'bold' }}>Rooms:</p>

            {
             h.rooms.map(room => (
               <div>
                 <div>- {room.name}</div>
               </div>
             ))
            }
          </div>
        ))
      }
    </div>
  );
}

  • Related