Trying to fetch data from an API and display it on views using Axios and Vuex for state management. The code below can log the data but is unable to pass it to the view.
Changing from mounted() to changed() did not solve the issue.
Here's the source code: In ‘./store/modules/form.js’ :
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
const state = {
posts: [],
};
const mutations = {
setPosts(state, posts) {
state.posts = posts;
}
};
const actions = {
loadPosts({ commit }) {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => response.data)
.then(posts => {
commit("setPosts", posts);
console.log(posts);
});
}
};
export default {
//namespaced: true,
state,
mutations,
actions
};
In './store/index.js :
import Vuex from "vuex";
import Vue from "vue";
import form from "./modules/form";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
form
}
});
In ‘components/Posts.vue’ :
<template>
<div>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr v-for="post in posts" :key="post.id">
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.body }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "PostsPage",
computed: mapState(["posts"]),
mounted() {
this.$store.dispatch("loadPosts");
},
};
</script>
If you have any insights or solutions, I would greatly appreciate your help. Thank you!