Currently, I am working on a project that utilizes Laravel and Vuejs to function as a Single Page Application (SPA). Within the admin page where I manage posts, I display a list of posts from the database using Vuex and Axios requests. There is also a button to delete a post.
However, when I delete a post, the list does not refresh automatically, and I have to manually refresh the page. Why is Vuex not updating the state?
backend/post/index.vue
<template>
<div class="post-index">
<h1>All Posts</h1>
<router-link :to="{ name: 'posts.create' }" class="nav-link" active-class="active">
<p class="new-post-btn">
Create a New Guide
</p>
</router-link>
<table class="table post-table">
<thead>
<tr>
<th scope="col">
#
</th>
<th scope="col">
Title
</th>
<th scope="col">
Is Publish
</th>
<th scope="col">
Created At
</th>
<th scope="col">
Actions
</th>
</tr>
</thead>
<tbody>
<tr v-for="guide in guides.post" v-bind:key="getPosts">
<th scope="row">
{{ guide.id }}
</th>
<th>{{ guide.title }}</th>
<th>{{ guide.is_publish }}</th>
<th>{{ guide.created_at }}</th>
<th>
<i class="fas fa-times" />
<button class="edit-button">
<router-link :to="{ name: 'posts.create' }">
<fa icon="edit" fixed-width />
</router-link>
</button>
<button class="delete-button" @click="deletePost(guide.id)">
<fa icon="times" fixed-width />
</button>
<button class="publish-button">
<fa icon="paper-plane" fixed-width />
</button>
</th>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
data () {
return {
guides: null
}
},
computed: {
...mapGetters({
posts: 'post/post'
})
},
beforeCreate () {
this.$store.dispatch('post/fetchPosts')
},
created () {
this.getPosts()
},
methods: {
getPosts () {
this.guides = this.$store.state.post
},
deletePost (postId) {
this.$store.commit('DELETE_POST', postId)
}
}
}
</script>
store/module/post.js
import axios from 'axios'
import * as types from '../mutation-types'
// State
export const state = {
post: null
}
// Getters
export const getters = {
post: state => state.post
}
export const mutations = {
[types.SAVE_POST] (state, { post }) {
axios.post('/api/posts/store', {
post
})
state.post = post
},
[types.DELETE_POST] (state, id) {
var index = state.post.findIndex(p => p.id === id)
state.post.splice(index, 1)
},
[types.FETCH_POST_SUCCESS] (state, { post }) {
state.post = post
},
[types.FETCH_POST_FAILURE] (state) {
state.post = null
}
}
export const actions = {
savePost ({ commit, dispatch }, payload) {
commit(types.SAVE_POST, payload)
},
async fetchPosts ({ commit }) {
try {
const { data } = await axios.get('/api/posts/index')
console.log(data)
commit(types.FETCH_POST_SUCCESS, { post: data })
} catch (e) {
commit(types.FETCH_POST_FAILURE)
}
},
deletePost ({ commit }, post) {
axios.delete('/api/posts/delete/' + post.id)
.then(function () {
commit(types.DELETE_POST, post)
})
}
}
Is there a more efficient way to handle this situation?