Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 878
rileyjsumner Avatar asked Nov 19 '19 04:11

rileyjsumner


People also ask

How do you assign a value to a prop in Vue?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

How do I transfer data from components to Vue?

VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!

How do you bind variables in Vue?

If we want to bind any variable, we can simply use Vue. js's double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance. Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.


1 Answers

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"
  });
 }
like image 70
Satyam Pathak Avatar answered Nov 15 '22 06:11

Satyam Pathak