A
A
Andrew2019-02-23 23:22:23
JavaScript
Andrew, 2019-02-23 23:22:23

Why does Vue.js return __ob__: Observer?

API:

created () {
    this.loadProfile()
  },
getPosts(author) {
    return axios.get(`${options.serverUrl}/posts/${author}`)
  },

Component:
async loadPosts () {
      const response = await services.getPosts(this.$route.params.id)
      this.posts = response.data
    },

And as a result, response.data = [__ob__: Observer]. That is, Vue does not wait for the given request to complete. Why?
The most important oddity is that this happens when the page is reloaded through the browser. If there is a reload through HotReload (when editing), or when going through routes, then the method works as it should and returns the expected values.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Kornilov, 2019-02-24
@KorniloFF

axios.get does not return a response, but a Promise
Therefore, we should try:

async loadPosts () {
      await services.getPosts(this.$route.params.id).then((response) => {this.posts = response.data})
    },

K
karambafe, 2019-02-24
@karambafe

Pavel Kornilov wrote everything correctly, the get method of axios is asynchronous, it returns a promise.
Therefore, the getPosts method also needs to be made asynchronous:

async getPosts(author) {
   try {
     const { data } = await axios.get(`${options.serverUrl}/posts/${author}`);
     return data; 
  } catch(error) {
     return error; // важный момент, что будет возвращать функция при ошибках выполнения запроса на сервер
  }
 },

Made a small example on codeSanbox , App.vue file.
The console shows the difference between the output for the current getPosts method and the new getPostsAsync
ps
From the context of this example, in my opinion, the getPosts method is rather useless - it increases the level of abstraction, but does not provide a full understanding of the code.
I would make a request to the server directly in the loadPosts method:
async loadPosts () {
  this.loading = true; // вешаем лоадер на момент асинхронного запроса

  try {
     const { data } = await axios.get(`${options.serverUrl}/posts/${this.$route.params.id}`);
     this.posts = data;
     this.loading = false;
  } catch(error) {
     // делаем что-то в случае ошибки
     this.loading = false;
  }
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question