Ad

VueJS Fetch Promises

- 1 answer

I have a component:

Vue.component('mail-list', {
  props: ['userInbox'],
  template:
  `
  <div>
    <p>{{userInbox}}</p>
  </div>
  `
  });

I want to print in p tag props content which is the result of created function

let options = {
  el: "#app",
  data: {
    pollingId: null,
  },

  created: function() {

    let users = fetch('/inbox')
    .then(response => response.json())
    .then(aJson => {return (aJson)})
    this.userInbox = users
  }
}
let vm = new Vue(options);

But this is only returning a promise which I can not work with.

Promise {<pending>}

Promise has this content:

{ '1':
   Mail {
     id: 1,
     from: '[email protected]',
     to: '[email protected]',
     subject: 'Hi Mar',
     body: 'This is a test from pep to mar',
     timestamp: 1590647288599 },
  '6':
   Mail {
     id: 6,
     from: '[email protected]',
     to: '[email protected]',
     subject: 'By Mar',
     body: 'This is a test from nil to mar',
     timestamp: 1590647288599 } }

I have to display in p tag the from and subject attributes of each.

Ad

Answer

First, don't forget to register userInbox in your data. Second, assign it in promise callback

let options = {
  el: "#app",
  data: {
    pollingId: null,
    userInbox: ''
  },

  created: function() {

    let users = fetch('/inbox')
    .then(response => response.json())
    .then(aJson => {
      this.userInbox = aJson
    })

  }
}
let vm = new Vue(options);
Ad
source: stackoverflow.com
Ad