5

I'm trying to set the data() value in a Vue instance to a value retrieved from a Promise that is returned from a mongodb api call. I'm able to retrieve the data I'm trying to implement, however am struggling to use it in the data() field so that I can access it in the template.

Some of the solutions I've found from vue2 don't seem to work in this instance. Thanks in advance.

Vue

<template>
  <Article :title=posts[0].title></Article>  // Another Vue component
</template>

let stories;

export default {
       data() {
            return {
                posts: {}
            }
       },
        methods: {
            loadPosts() {
                stories = getPosts(); // makes an api request to a mongodb that returns a Promise
                stories.then(function(response) {
                    this.posts = response.posts;
                    console.log(response.posts[0].title); // "My Post Title"
                });

            }
        },
        mounted() {
            this.loadPosts();
        }
}

The error I receive says

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

in reference to this.posts = ...

Mahesh Waghmare
  • 726
  • 9
  • 27
rileyjsumner
  • 523
  • 1
  • 8
  • 21

1 Answers1

7

this get the window reference as you are using dynamic scope, use lexical scope binding to get this as Vue

For your specific reference and eagerness to read more about scopes - follow this Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)

For lexically binding use arrow-function

loadPosts() {
  stories = getPosts(); 
  stories.then(response => {
      this.posts = response.posts;
      console.log(response.posts[0].title); // "My Post Title"
  });
 }
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52