0

I'm using the Yelp Fusion API for a project of mine. I'm using two different types of calls: one that returns an array of restaurant IDs given a location, and one that returns restaurant details given a restaurant ID. Essentially, I want to get the array of IDs and then use these IDs to replace the item in the array with the restaurant's details, so that I end up with an array of restaurant detail items. I'm using Axios for this. Here's the relevant part of the code.

//Run the Business Search API to get 50 results, based on location and filters

function getRestaurantsFromYelp() {

  var axios = require('axios');

  var config = {
    method: 'get',
    url: `https://api.yelp.com/v3/businesses/search?limit=50&latitude=${lat}&longitude=${long}`,
    headers: { 
      'Authorization': 'Bearer [[authorization token]]'
    }
  };
  
  axios(config)
  .then(async function (response) {
    var restaurants = response.data.businesses      //array of 50 restaurants
    try {
      for (let i = 0; i < 3; i++) {
        let id = restaurants[i].id;
        let details = getRestaurantDetails(id);
        restaurants[i] = details;
      }
    } catch (error) {
      console.log(error)
    }
    setRestaurantData(((restaurants)));
  })
  .catch(function (error) {
    console.log(error);
  });


}

async function getRestaurantDetails(id) {
var axios = require('axios');

  var config = {
    method: 'get',
    url: `https://api.yelp.com/v3/businesses/${id}`,
    headers: { 
      'Authorization': 'Bearer [[authorization token]]'
    }
  };

  await axios(config)      
  .then(function (response) {
    return response.data;
  })
  .catch(function (error) {
    console.log(error);
  });

  return;
}

I'm pretty new to React Native and I know the issue lies somewhere in my async/await stuff. Right now, the variable 'details' comes out as undefined and the return of the business details happens after that (as checked by print statements). Any help would be appreciated!

Note: Eventually I need all 50 of the business details, but as I'm having trouble right now I've set the 'for' loop to just run through the first 5 elements.

  • Change let details = getRestaurantDetails(id); to let details = await getRestaurantDetails(id); – caslawter Jul 13 '22 at 05:14
  • I don't see many people using .then and async/await in the same code. It's easier mentally to use one or the other I think. It might help you organize it. – Abe Jul 13 '22 at 08:47

0 Answers0