Anthony Watson
Anthony Watson

Reputation: 108

Vue axios (and fetch) responses not passing into data property

I have a Vue (2.2.1) component that should display a membership directory by making a request to a Laravel API. The request succeeds, and the response is correct when I console.log it. Likewise, the API request succeeds in Postman and the JSON object is correctly formatted. But, the response won't pass into the variable in the Vue instance data object to which I attempt to assign it. My code:

<template>
  <div>
    {{ entries }}
  </div>
</template>

<script>
  export default {
    name: 'directory',
    data() {
      return {
        entries: []
      }
    },
    created() {
      this.getEntries()
    },
    methods: {
      getEntries: function() {
        axios.get('/api/directory')
          .then(response => {
             this.entries = response.data;
          });
      }
    }
  }
</script>

When I load the page (after npm run dev), empty brackets representing the initial state of entries (an empty array) is displayed and not the raw JSON data. (I'm just testing now, not yet styling or building the table). However, if I add a console.log(this.entries) or console.log(response) or console.log(response.data), the correct form of the JSON is displayed in console and there are no errors.

I have replaced the axios code with the appropriate fetch code, including the ->json() line and get the same results. I have also used a "practice" API (JSONPlaceholder) to make sure it wasn't a problem with my API and likewise got the same results. This suggests that I'm doing something wrong in my Vue component <script>, but after hours of searching SO, Google, and Vue.js forum, I'm not finding anything. The closest matching link (Vue.js cannot set data returned from external axios response) was of no help, unfortunately.

Upvotes: 1

Views: 2310

Answers (1)

Michael
Michael

Reputation: 5048

I would make your entries a computed property so it will update on the call, it seems like your template is not updating a computed property may solve this. Try this:

data(){
   return {
      dataEntries: null
    }

computed: {
   entries(){
       if (dataEntries) return dataEntries
       return []
    }

Upvotes: 1

Related Questions