nick
nick

Reputation: 1178

Having trouble displaying API results

So I'm learning API's and I am using https://calendarific.com api and I have fetched the api and am able to console log the results. My problem is actually displaying the result of the api.

I have tried to save the name to a variable (like this)

myVariable.innerHTML = data.name;

myVariable holds an object with nested arrays: {holidays: [Arrays]} but I'm having trouble displaying it.

If it helps here is my code:

  let countrySelect = document.getElementById('country-select');
  let holidayName = document.querySelector('holiday-name')
  let holidayDesc = document.querySelector('holiday-desc')


  const api = `https://calendarific.com/api/v2/holidays?api_key=<my api key>&country=ca&year=2019`;


// Get results on click
countrySelect.addEventListener('click', function() {
  fetch(api)
  .then(response => {
    return response.json();
   })
    .then(data => {
      holidayName = data.response;
      console.log(data)
    });
  })

Upvotes: 2

Views: 223

Answers (1)

kedar sedai
kedar sedai

Reputation: 1722

 var btn = document.querySelector('#option0');
 var holiday = document.querySelector('holiday-name');
 var holidayDesc = document.querySelector('holiday-desc');

btn.addEventListener('click', function fetchApi(){
    fetch('https://calendarific.com/api/v2/holidays?api_key=<my api key>&country=ca&year=2019')
    .then(res => res.json())
    .then(data => {
       holiday.innerHTML = data.response.holidays[0].name;
        //console.log(data);
    })
    .catch(err => console.log(err));
});

Hope this helps

Upvotes: 1

Related Questions