Just want to say that I am became familiar with vue not so long ago.
Now I am having a problem.
I fetch data from the server.
// store
import PostService from '../services/PostService'
export default {
state: {
posts: [],
},
actions: {
async getPost() {
const response = await PostService.fetchPosts();
console.log(response.data.posts);
this.posts = response.data.posts
}
}
}
There is an array for data and a request to the server.
In response
, the data comes.
// vue component
<template>
<section class="posts--wrap">
<div class="posts wrapper">
<h1>Posts</h1>
<div
class="posts__item--wrap"
v-if="this.allPosts.length"
>
<h3>List of posts</h3>
<div
v-for="(post, index) in allPosts"
:key="index"
class="posts__item">
<h3 class="posts__item-title">{{post.title}}</h3>
<p class="posts__item-text">{{post.description}}</p>
</div>
</div>
<div
v-else
class="posts__item-error"
>
<h3>There are no posts ... Lets add one now!</h3>
<router-link tag="div" :to="{name: 'Add'}">
<a>Add new post ;)</a>
</router-link>
</div>
</div>
</section>
</template>
<script>
import { mapState } from 'vuex';
import { mapActions } from 'vuex';
export default {
name: 'PostPage',
data () {
return {
}
},
computed: mapState({
allPosts: state => state.posts.posts
}),
methods: {
...mapActions({
getAllPosts: 'getPost'
})
},
mounted() {
console.log(this.allPosts);
this.getAllPosts();
}
}
</script>
If add something to state.posts
, it will be displayed on the page.
But I can't figure out how to get the data from the response
into the posts
I ask for help, or hints.
Thank!
UPD
Made changes for which displays the response
response.log
(2) [{…}, {…}]
0: {_id: "5be4bbfaad18f91fbf732d17", title: "Title post 1", description: "esxdfgdfghj"}
1: {_id: "5be490f930fba81a704867f6", title: "2312", description: "312312312"}
length: 2
__proto__: Array(0)
You did wrong in your action getPost
, the proper way to change a state through an action is to commit a mutation
using action context
parameter like this:
...
mutations: {
setPosts(state, posts) {
state.posts = posts;
},
},
actions: {
async getPost(context) {
/* ... */
context.commit('setPosts', response.data.posts);
}
},
...