Currently, I am in the process of developing a website that allows users to upload posts. Each user has their own profile page where they can view the posts they have liked and the posts they have created. On a created post, there is a delete button. However, when I delete a post, it only gets removed from the backend. The post still appears on the home page and profile page (unless I refresh the page). I'm trying to figure out how to update these components without having to refresh the entire page.
I am facing challenges with re-rendering the components as I am fairly new to programming. When using the delete method, I need to update three components: Home.vue, Posts.vue, and Profile.vue.
This is the HTML for the delete button in my profile component/page:
<v-container class="mt-3" v-else>
<v-flex xs12>
<h2 class="font-weight-light">
Created posts
<span class="font-weight-regular">({{ userPosts.length }})</span>
</h2>
</v-flex>
<v-layout row wrap>
<v-flex xs12 sm6 v-for="post in userPosts" :key="post._id">
<v-card class="mt-3 ml-1 mr-2" hover>
<v-btn color="info" floating fab small dark @click="loadPost(post)">
<v-icon>edit</v-icon>
</v-btn>
<v-btn
color="error"
floating
fab
small
dark
@click="handleDeleteUserPost(post)"
>
<v-icon>delete</v-icon>
</v-btn>
<v-img
height="30vh"
:src="post.imageUrl"
@click="goToPost(post._id)"
></v-img>
<v-card-text>{{ post.title }}</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
Here are the lifecycle hooks located under "methods":
handleDeleteUserPost(post) {
this.loadPost(post, false);
const deletePost = window.confirm("Do you want to delete your post?");
if (deletePost) {
this.$store.dispatch("deleteUserPost", {
postId: this.postId,
});
}
}
The Vuex store component's deletion functionality is located under "action":
deleteUserPost: ({ state, commit }, payload) => {
apolloClient
.mutate({
mutation: DELETE_USER_POST,
variables: payload,
})
.then(({ data }) => {
const index = state.userPosts.findIndex(
(post) => post._id === data.deleteUserPost._id
);
const userPosts = [
...state.userPosts.slice(0, index),
...state.userPosts.slice(index + 1),
];
commit("setUserPosts", userPosts);
})
.catch((err) => {
console.error(err);
});
}
Mutations defined in the "store":
mutations: {
setPosts: (state, payload) => {
state.posts = payload;
},
setSearchResults: (state, payload) => {
if (payload !== null) {
state.searchResults = payload;
}
},
setUser: (state, payload) => {
state.user = payload;
},
setUserPosts: (state, payload) => {
state.userPosts = payload;
},
setLoading: (state, payload) => {
state.loading = payload;
},
setError: (state, payload) => {
state.error = payload;
},
setAuthError: (state, payload) => {
state.authError = payload;
},
clearUser: (state) => (state.user = null),
clearError: (state) => (state.error = null),
clearSearchResults: (state) => (state.searchResults = []),
},