0

I am a bit of a newbie to ES6 Javascript and have been trying to write a module to grab some data from the FourSquare API using fetch() and stick the results into some list items.

The code for the module is below:

export default (config) => class fourSquare {

constructor(){
    this.clientid = config.client_id;
    this.secret = config.client_secret;
    this.version = config.version;
    this.mode = config.mode;
}

getVenuesNear (location) {
    const apiURL = `https://api.foursquare.com/v2/venues/search?near=${location}&client_id=${this.clientid}&client_secret=${this.secret}&v=${this.version}&m=${this.mode}`;

    fetch(apiURL)
        .then((response) => response.json())
        .then(function(data) {
            const venues = data.response.venues;


            const venuesArray = venues.map((venue) =>{
                return {
                    name: venue.name,
                    address: venue.location.formattedAddress,
                    category: venue.categories[0].name
                }
            });


            const venueListItems = venuesArray.map(venue => {
                return `
                    <li>
                        <h2>${venue.name}</h2>
                        <h3>${venue.category}</h3>
                    </li>
                `;
            }).join('');

            return venueListItems;


        })
    .catch(function(error) {
        //console.log(error);
    });
}

}

I am importing this module in another file and attempting to use the returned list items:

    const venueHTML = fourSquareInstance.getVenuesNear(locationSearchBox.value);

    console.log(venueHTML);

But the result is always undefined. I know that the code within the module is OK because if I change: return venueListItems to console.log(venueListItems) the list items are logged to the console. I believe this may be due to the asynchronous nature of fetch() but not sure how to re-factor my code to return data from the getVenuesNear function.

1 Answer 1

3

You have to return the result of fetch():

return fetch(apiURL)

Also, when you call the getVenuesNear function, you have to use the then method to access the result:

fourSquareInstance.getVenuesNear(locationSearchBox.value).then(venueHTML => {
  console.log(venueHTML);
});
Sign up to request clarification or add additional context in comments.

Comments

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.