Can someone assist me with implementing component re-rendering in VueJS?

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 = []),

},

Answer №1

Uncertain if the following steps will completely resolve the issue, but it's worth a shot:

const userPosts = [
  ...state.userPosts.slice(0, index),
  ...state.userPosts.slice(index + 1),
];
commit("setUserPosts", userPosts);

Change to:

commit("removeUserPost", index)

Additionally, you should create the mutation as shown below:

removeUserPost(state, index) {
  state.userPosts.splice(index, 1);  // <-- `splice` not `slice` here
}

If this doesn't resolve the issue, verify that you are utilizing userPosts in the component like so:

computed: {
  userPosts() {
    return this.$store.state.userPosts;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

Getting a box-shadow programmatically in Opera can be achieved by using the appropriate CSS

Trying to achieve the same effect with jQuery: item.css("-o-box-shadow") or: item.css("box-shadow") However, the result is an empty string. In Webkit and Gecko browsers it works by using "-webkit" and "-moz" prefixes respectively. How can this be ach ...

Can dynamically generated files be cached on the client side?

I am currently developing a project that utilizes websockets. The primary server, which serves as both a web and websocket server, functions as a forwarding hub to other websocket servers. These secondary websocket servers do not need to have their own web ...

Collect input from the user for multiple lists and send them to PHP for additional processing

I'm struggling to find the error in this code... I keep getting "undefined index user_list" as the error message. Essentially, I am trying to allow users to input values into a list and then store that entire list in a database. <?php if(isset($_ ...

Retrieve items from the parent row of selected checkboxes

Within my table, I have the following row. <tr class="data_rows" ng-repeat='d in t2'> <td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td> &l ...

How can I duplicate a specific row within DataTables?

I have successfully implemented a feature that allows me to delete a selected row in my application. Now, I am looking to add functionality to duplicate or clone the selected row. The process of adding rows to DataTables can sometimes be challenging becaus ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

Can you tell me the result of running path.resolve('.')?

What happens when we use the resolve('.') function in node.js? I recently studied the path npm documentation and discovered that the resolve function creates an absolute path by going from right to left, which may include the current working dir ...

What is the process for declaring a variable and then using it within a concealed input field?

I have a JavaScript code that performs mathematical calculations, and I need to extract the final result to include it in a form. My plan was to utilize an <input type="hidden" name="new total"> field to store this result. I am looking to retrieve th ...

Divide the array object based on the "@" symbol

i am in possession of the following array object let old_array = { "valone": "facebook", "notification": "new message! @[email protected] @[email protected]" } i aim to extract all users with @ sign into a new array like displayed below le ...

Display the current page as it appears in AngularJS

I attempted to utilize the ngPrint directive from https://github.com/gilf/ngPrint for printing purposes. However, when I print the page, the design collapses entirely. Is there a solution to maintain the page layout when printing? Please note that Angula ...

Angularjs Directive content not bound to isolated scope

I'm currently exploring directives and my goal is to bind a value to my grandchild component, then update the parent element. However, I've encountered an issue as this code does not propagate up to the root. var myApp = angular.module('m ...

The jQuery hover function is not functioning properly on page load in Firefox

While this code is functioning smoothly in Chrome and IE, it seems to be encountering issues in Firefox! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> JS: $(window).load(function(){ $("#bosti ...

Node.js and Express: troubleshooting slow page loading issues

Currently, I am following a PluralSight tutorial on Node.Js/Express. However, I am facing an issue with my admin router page as it seems to be loading indefinitely without showing any error messages. This page is supposed to run on localhost:4000. Interest ...

Engage in a conversation with a specific individual on the internet using node.js

Looking to implement a chat feature with specific online users similar to Facebook or Gmail using node.js and socket.io. Can anyone assist me with this? Thanks in advance! Client.html <html> <head> <title>My Chat App</title> <d ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

transferring an EJS object to a Vue function

When working with an Express app, I encountered an issue where I need to pass an object to a Vue method. Below is the snippet of EJS template: <%-item.price%> <button v-on:click="add_to(<%=item%>)" class="float-right">Add...</button& ...

if statement based on the conditions set in the CSS

I've been struggling with an issue for a whole day now, and I just can't seem to solve it. I have a few keydown functions that change the background image under certain conditions when the 'active' class is not present. Here's an e ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

Attempting to transfer a property from one page to another using the Link component in NextJS

Currently, I have a page containing six Link elements that are meant to redirect to the same destination but with different props based on which link is clicked. To pass props, this is how I've implemented it: <Link href={{ pathname: '/pro ...