[Vuejs]-Console log undefined after fetching api in Vue

2๐Ÿ‘

โœ…

fetch returns a promise containing the response res.
(This is just an HTTP response, not the actual JSON.)

To extract the JSON body content from the response, we use the json() method

You can read more about using fetch.

fetchTickets() {
    fetch('/api')
    .then(res => res.json()) //returning a promise To extract the JSON body content from the response
    .then(resJson => {
        this.tickets = resJson
        console.log(resJson);
    }) 
}
๐Ÿ‘คAshish

2๐Ÿ‘

Return your data before going in second promise.

fetchTickets() {
    fetch('/api')
    .then(res => {
        this.tickets = res.json;
        return res;
    })
    .then(res => {
        console.log(res.json);
    }); 
๐Ÿ‘คZooly

2๐Ÿ‘

add the return statement in the first promise

fetch('/api')
  .then(res => {
      return res.json();
   })
   .then(tickets => {
     // tickets is a local variable scoped only here
     console.log(tickets);
   }) 
๐Ÿ‘คKarim

Leave a comment