codex
codex

Reputation: 87

pass object from function

I'm going to be able to retrieve the data by calling getTicket via listTicket

listTicket :

listTicket()
   {
     objectTicket = this.getTicket();
     objectTicket.map((userData)=>{
      alert(userData.id)
    })
}

getTicket Code:

async getTicket () {
      return await fetch('url', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            uid: '1',
            type: '0'
          })
      })
        .then((response) => {return response.json()})
        .then((responseJson) => {
          return responseJson;
        })
        .catch((error) => {
          alert(error);
        });
    }

I get this error:

typeerror objectTicket.map is not a function

Upvotes: 1

Views: 70

Answers (4)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

An async function returns a promise and resolves with the return value of the function.

So, when you are calling the listTicket function. the listTicket function is returning the promise Object along with the return value{VIEW} and that is creating the problem.

To solve the problem you should set the objectTicket value to a state variable and loop over state variable.

Upvotes: 0

Maciej Wojsław
Maciej Wojsław

Reputation: 403

As getTicket is returning a Promise listTicket method should be also async.

async listTicket() {
   objectTicket = await this.getTicket();
   objectTicket.map((userData)=> {
      alert(userData.id)
   });
}

Upvotes: 1

Azamat Zorkanov
Azamat Zorkanov

Reputation: 819

From getTicket method you're getting Promise, so you should to subscribe to it:

listTicket() {
     objectTicket = this.getTicket();
     objectTicket.then((res) => { 
       res.map((userData)=> {
          alert(userData.id)
       })
     })
}

Upvotes: 2

wogsland
wogsland

Reputation: 9508

The issue here is that getTicket() is a function that returns a Promise whereas map is defined on arrays.

Upvotes: 1

Related Questions