-1

I have an API call in the photoRetriever function. I saved the API object to the variable named "data" and I want to access this in the App class. I am trying to access an image in the API that is a method titled "url". It says that the variable data is not defined when I try to access it in the _generateMarkup method. What is the best way to define this variable so I can easily gain access to it outside of the function?

Code:

const photoRetriever = async function() {
    try {
        const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=MHfiCXEcU8gFYbgux8MWX0nBFYRtzJsbefF4eq5R');
        const data = await res.json();
        console.log(data.url)
       

    } catch(err) {
        alert(err)
    }
}
photoRetriever();

class App {
    _parentEl = document.querySelector('.parent__el');
    constructor() {
        this._generateMarkup();
        

    }



    _generateMarkup() {  
        const markup = `
            <div class="space__photo">
              <img src="${data.url}" alt="" />
            </div>
        
        `;

        this._parentEl.insertAdjacentHTML('afterbegin', markup);

    }
}

const app = new App()
Austin
  • 99
  • 8
  • 1
    You can declare the variable at the top outside the function scope then it should be accessible – Amit Gupta Mar 16 '22 at 12:43
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Liam Mar 16 '22 at 12:45

1 Answers1

0

you have to return the value of the data into other variable with higher scope you can do something like this:

const photoRetriever = async function() {
    try {
        const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=MHfiCXEcU8gFYbgux8MWX0nBFYRtzJsbefF4eq5R');
        const data = await res.json();
        console.log(data.url)
        return data

    } catch(err) {
        alert(err)
    }
}


class App {
    _parentEl = document.querySelector('.parent__el');
    constructor(data) {
        this.data = data;
        this._generateMarkup();
        
        

    }



    _generateMarkup() {  
        const markup = `
            <div class="space__photo">
              <img src="${this.data.url}" alt="" />
            </div>
        
        `;

        this._parentEl.insertAdjacentHTML('afterbegin', markup);

    }
}
async function main(){
const data = await photoRetriever();
const app = new App( data )

}

ShobiDobi
  • 179
  • 1
  • 13