Wilker
Wilker

Reputation: 17

Async await its showing undefined

export default class Search {
constructor(query){
    this.query = query;
}

async getResults() {
    const API_KEY = "1d4e862be156056d16d3390378173c21";

    await fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${this.query}`)
    .then(res => res.json())
    .then(data => {
        const result = data.recipes;
        console.log(result);
    })
    .catch(error => alert('Receive Data Failed'))

};

}

import to here..

const state = {};

const controlSearch =  async () =>{

    const query = 'pizza'

    if(query){

        state.search = new Search(query);

        await state.search.getResults();

        console.log(state.search.result);

    }
}

it store the data from getResults method into a variable. i wondering that it returning a undefined when i called it from state.search.result

Upvotes: 1

Views: 282

Answers (1)

trincot
trincot

Reputation: 350137

You never assign anything to state.search.result

Replace:

const result = data.recipes;

with:

this.result = data.recipes;

That will do the trick. However, it is better design to return values as promise resolution values:

getResults() { // drop the async; just return the promise
    const API_KEY = "1d4e862be156056d16d3390378173c21";

    return fetch(`https://www.food2fork.com/api/search?key=${API_KEY}&q=${this.query}`)
//  ^^^^^^
    .then(res => res.json())
    .then(data => this.result = data.recipes);
//                ^^^^^^^^^^^ (return it)
    .catch(error => alert('Receive Data Failed'))
};

And in your main code:

    state.search = new Search(query);
    console.log(await state.search.getResults());

Upvotes: 1

Related Questions