I was practicing and learning about vuejs, specifically pagination.
I learn how to do it, and implemented it when I made the api calls in the component, then I moves the function to the actions in vuex, and mapped, them, now my pagination is not even showing up.
I wonder where I made the mistake ???
I have carefully paid attention to every single detail, and read about mutatioons, and actions, I do feel like I am doing everything right, I don't even have any mistakes showing up on the console. this is very wierd
my postModule
import axios from "axios";
export const postModule = {
state: () => ({
posts: [],
page: 1,
limit: 10,
totalPages: 0,
}),
mutations: {
setPosts(state, posts) {
state.posts = posts;
},
setPage(state, page) {
state.page = page;
},
setTotalPage(state, totalPages) {
state.setTotalPage = totalPages
},
},
actions: {
async fetchPosts( {state, commit}) {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts", {
params: {
_page: state.page,
_limit: state.limit,
},
});
commit('setTotalPage', Math.ceil(response.headers["x-total-count"] / state.limit));
commit('setPosts', [...state.posts, ...response.data]);
} catch (e) {
console.log(e);
}
},
async loadPosts({
state,
commit
}) {
try {
commit('setPage', state.page + 1)
setTimeout(async () => {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts", {
params: {
_page: state.page,
_limit: state.limit,
},
});
commit('setTotalPage', Math.ceil(response.headers["x-total-count"] / state.limit));
commit('setPosts', [...state.posts, ...response.data]);
});
} catch (e) {
console.log(e);
}
},
},
namespaced: true,
}
<<<<<component >>>>
<template>
<div>
<h1>Page with the posts</h1>
<post-list :posts="posts" />
</div>
<div class="page__wrapper">
<div
v-for="pageNumber in totalPages"
:key="pageNumber"
class="page"
:class="{
'current-page': page === pageNumber,
}"
@click="changePage(pageNumber)"
>
{{ pageNumber }}
</div>
</div>
</template>
<script>
import PostList from "@/components/PostList";
// import axios from 'axios';
import { mapState, mapMutations, mapActions } from "vuex";
export default {
components: { PostList },
data() {
return {
// posts: [],
// page: 1,
// limit: 10,
// totalPages: 0,
};
},
methods: {
changePage(pageNumber) {
this.page = pageNumber;
this.fetchPosts();
},
...mapMutations({
setPage: "setPage",
}),
...mapActions({
// loadPosts: "post/loadPosts",
fetchPosts: "post/fetchPosts",
}),
},
watch: {
page() {
this.fetchPosts();
},
},
mounted() {
this.fetchPosts();
},
computed: {
...mapState({
posts: (state) => state.post.posts,
page: (state) => state.post.page,
limit: (state) => state.post.limit,
totalPages: (state) => state.post.totalPages,
}),
},
};
</script>
<style scoped>
.page__wrapper {
display: flex;
margin: 15px;
}
.page {
border: 1px solid black;
padding: 10px;
}
.current-page {
border: 2px solid red;
font-size: x-large;
}
</style>