0

I have fetched data by using axios. But it seems like vue component doesn’t update after click event and when the data changed. So I have to refresh the page in order to update data on the page. Do you have any simple way to solve this problem?

This is the code from template.

<template>
  <div class="container">
    <h1>Latest Posts</h1>
    <div class="create-post">
        <label for="create-post">Add new post...</label>
        <input type="text" id="create-post" v-model="text" placeholder="Create a post">
        <button v-on:click="createPost">Post!</button>
    </div>

    <hr>

    <p class="error" v-if="error">{{ error }}</p>

    <div class="posts-container">
      <div class="post" v-for="(post, index) in posts" v-bind:item="post" v-bind:index="index" v-bind:key="post._id">
        {{`${post.createdAt.getDate()}/${post.createdAt.getMonth()}/${post.createdAt.getFullYear()}`}}
        <p class="text" id="example">{{post.text}}</p>
      </div>
    </div>

  </div>
</template>

This is the code from script


<script>
import PostService from '../PostService';

export default {
  name: 'PostComponent',
  data() {
    return {
      posts: [],
      error: '',
      text: ''
    }
  },
    computed: {
      postText: function() {
        return this.post.text
      }
    },
    watch: {

    },
  async created() {
    try {
      this.posts = await PostService.getPosts();
      console.log(this.$el.textContent) 
    } catch(err) {
      this.error = err.message;
    }
  },
  methods: {
    async createPost() {
      await PostService.insertPost(this.text);
      this.post = await PostService.getPosts();
    }
  }
}
</script>

1 Answer 1

1

I suspect this line: this.post = await PostService.getPosts(); should be this.posts = await PostService.getPosts(); Here's a Codepen link. If that doesn't fix your issue, ensure the PostService returns correct objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you so much. That was a stupid mistake from me. But I was just wondering why I didn't get any error message that 'post' is not defined. Anyway thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.