After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue?
Below is the code snippet from the 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>
And here's the script section of the code:
<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>