rileyjsumner
rileyjsumner

Reputation: 563

Set data object to value from Promise in Vue 3

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 = ...

Upvotes: 6

Views: 6364

Answers (1)

Satyam Pathak
Satyam Pathak

Reputation: 6912

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"
  });
 }

Upvotes: 8

Related Questions