0

I am using JS to fetch some data through Axios. I want that response data outside the axios body. I have declared a global (let) var tagData outside the block. when I am logging value of tagData outside the axios its showing undefined. how can I access the response.data outside axios block?

let data = ""
let tagData;
let movie;

const section = document.createElement('section');
section.setAttribute('class', 'section');
const container = document.createElement('div')
container.setAttribute('class', 'container is-desktop')



axios.get('https://dashletter-backend.herokuapp.com/blog/?category=allcategory')
    .then((response) => {
        tagData = response.data;
        console.log(tagData[0].name)
        for (movie in tagData) {
            const tagme = document.createElement('span')
            tagme.setAttribute('class', "tag is-rounded")
            tagme.setAttribute('id', "t" + movie)
            tagme.textContent = tagData[movie].name
            tagu.appendChild(tagme)

        }
    }
        , (error) => {
            console.log(error);

        });

console.log(tagData[0].name);  // Here tagData is undefined
  • It's because `console.log(tagData` executed before the promise is resolved which sets the value of `tagData`. – vatz88 Apr 17 '20 at 10:24
  • @vatz88 so where to put console.log? – Vishesh Dubey Apr 17 '20 at 10:31
  • Well, you should check out how promises work and asynchronous code is executed. You can put the log immediately after you set tagData or chain another then() and log it in there – vatz88 Apr 17 '20 at 10:37

0 Answers0