wobsoriano
wobsoriano

Reputation: 13432

How to set value of array object property inside a promise in VueJS?

I am using feathersjs with feathers-client with VueJS and I get a Cannot set property 'employees' of undefined typeerror. This is my code:

<template>
  <ul>
    <li v-for="employee in employees">{{employee.name}}</li>
  </ul>
</template>

<script>
import feathers from 'feathers/client'
import socketio from 'feathers-socketio/client'
import hooks from 'feathers-hooks'
import io from 'socket.io-client'

const socket = io('localhost:3030')
var app = feathers().configure(hooks())
                    .configure(socketio(socket))
                    .configure(authentication({ storage: window.localStorage }));

export default {
 data() {
   return {
     employees: []
   }
 },
 mounted() {
     app.authenticate().then(function(response) {
          app.service('users').find().then(function(users) {
            this.employees = users.data
          })
        }, function(error) {
          console.log(error)
        })
   }
}

</script>

And when I run it I get

Uncaught (in promise) TypeError: Cannot set property 'employees' of undefined

in the console.

Am I doing something wrong here?

Upvotes: 1

Views: 629

Answers (1)

Traxo
Traxo

Reputation: 19002

this inside function points to that function so

 mounted() {
         var self = this; //add this line
         app.authenticate().then(function(response) {
              app.service('users').find().then(function(users) {
                self.employees = users.data //change this to self
              })
            }, function(error) {
              console.log(error)
            })
       }
    }

Upvotes: 2

Related Questions