0

So, I am trying to fetch API from Calendarific I fetch it and I get data in console here is the code below:

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

But I want to access specific data like. I want to access only the name and how can I do that? Code works fine but I faced problem to access specific data from API I tried holidays[0].name But it shows undefined What I am doing wrong here?

2
  • 1
    res -> res.json() Commented Apr 10, 2020 at 4:10
  • show us how the data looks like Commented Apr 10, 2020 at 4:13

1 Answer 1

2

When receiving JSON, instead of

.then(res => res.text())
.then(...

use

.then(res => res.json())
.then(...

Also, according to calendarific documentation, there's a response key you should query first:

console.log(data.response.holidays[0].name)
Sign up to request clarification or add additional context in comments.

3 Comments

Okay! Thank You I got it I thought for displaying data on the browser I need to use res.text() but now I am confused about in which condition I need to use res.text()?
When the URL you are querying return a text, use text, when it's a json, use json
You can post a new question

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.