Calling an object from an API in Javascript

Issue

This Content is from Stack Overflow. Question asked by Chioma Uche

This is my current result of this task**Please see the problematic lines comment. I’m having trouble getting the values of the currencies and languages from the API. I tried using ${data.currencies[0].name} and ${data.languages[0].name} but it still throws an error. **

'use strict';

const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');

///////////////////////////////////////
const getCountryData = function(country){
    const request = new XMLHttpRequest();
    // GET DATA
    request.open('GET', `https://restcountries.com/v3.1/name/${country}`);
    
    // SEND THE REQUEST
    request.send();
    
    // REGISTER A CALLBACK FUNCTION ON THE REQUEST OBJECT FOR THE LOAD EVENT
    request.addEventListener('load', function(){
        // CONVERT JSON CODE TO A JAVASCRIPT OBJECT 
        const [data]= JSON.parse(this.responseText);
    
        // ([data] is being destructured because it was an array that had an object in it, so now its just an object containing all the information)
    
        console.log(data);
    
        const html = `
        <article class="country">
        <img class="country__img" src="${data.flags.png}" />
        <div class="country__data">
          <h3 class="country__name">${data.name.common}</h3>
          <h4 class="country__region">${data.region}</h4>
          <p class="country__row"><span>👫</span>${(+data.population / 1000000).toFixed(1)} million</p>
          <p class="country__row"><span>🗣️</span>${data.languages}</p> //problematic line
          <p class="country__row"><span>💰</span>${data.currencies.name}</p> //problematic line
        </div>
      </article>
        `;
        countriesContainer.insertAdjacentHTML('beforeend', html);
        countriesContainer.style.opacity = 1;
    });
};

getCountryData('nigeria');
getCountryData('south africa');



Solution

check the answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?