What is the best way to automatically update a list of posts using vuex?

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?

Answer №1

The issue arises when the fetchPosts and handling of DELETE_POST are defined.

To resolve this, ensure that committing DELETE_POST either reloads or removes the specific element from this.$store.state.post.

Subsequently, the computed mapGetters will automatically update your posts.

Answer №2

After some troubleshooting, I was able to determine that the store itself was functioning properly. The issue actually stemmed from how I had integrated the Vue.js hooks within my component.

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

Enhancing the visual appearance of a date in Vue when filling input fields

How can I format a date in an input box populated with Vue from an object? This is the example code showcasing how the input box is populated using :vue <input type="text" id="Example" :value="v.date" spellcheck="false"> The date stored in the obj ...

Script for collapsing or expanding is non-functional

Although I am a beginner in Javascript coding, I am eager to learn more about it. I stumbled upon some tutorials on creating collapse/expand <div> blocks. After testing the code on jsfiddle, I found that it works fine there. You can find the code he ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

Tips for accurately extracting values from a decoded JSON

Hello, I am posting this query because I recently encountered an issue with json encoding in PHP. When using the json_encode() function, my original JSON data gets converted to strings instead of maintaining its original variable type. For instance, let&a ...

What are the best methods for concealing the URL or video source in JWPlayer 7 or Flowplayer version 6.0.5?

Is there a way to conceal the URL of a video from being viewed in the browser's inspect element? I'm looking for a method to encrypt it and prevent IDM from downloading the video. flowplayer("#fp-hlsjs", { key: "$**********", logo: "<?= Y ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

The session data is not persisting in the express-session package

I am currently learning about HTTPS and working on implementing a login/logout function. In this function, I store the userId in the session when I login using the POST method. However, when I try to retrieve user information for the next components usin ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

A guide on extracting the current website URL in a React application

I wanted to find a method to duplicate the text from a URL so that users could easily share the link with others. ...

Please click the provided link to display the data in the div. Unfortunately, the link disappearance feature is currently not

What I'm Looking For I want the data to be displayed when a user clicks on a link. The link should disappear after it's clicked. Code Attempt <a href="javascript:void(0);" class="viewdetail more" style="color:#8989D3!important;">vi ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

The issue persists with the Javascript AJAX POST Method as it fails to transmit values to the designated

I have been using Javascript AJAX to make a request to a php page and receive the output from that page. Interestingly, when I use the GET method in my AJAX call, everything works as expected. However, the issue arises when I try to use the POST method. B ...

Learn how to call class methods using jQuery events by utilizing the on() method

I'm attempting to create a reusable "component" using both HTML5 and accompanying JavaScript code that can be utilized multiple times. First, let's examine the HTML5 component code: <div class="listEditor" id="myStringList"> <div id="li ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Unlock the powers of Express, Passport, and Redis sessions!

Lately, I have been utilizing the default MemoryStore for my Express sessions and everything has been running smoothly. However, I encountered a setback where all session data was lost between restarts. To address this issue, I am now attempting to configu ...

``Within the template section, an image path is defined which includes a variable

I am facing an issue where I want to incorporate a variable into an image path within the template section of my component: <img :src="`@/assets/img/${variable}.svg`" /> While the ${variable} part functions correctly, the problem lies in the initia ...

What is the process for appending a URL parameter to the existing URL in a React application?

Presently, I am working within the Post component and using the Fetch API to retrieve data from the "/home" route. componentDidMount() { fetch('/home') .then(res => res.json()) .then((data)=> { console.log(data.ports) ...

Can you pass a specific function as a parameter in express.post()?

I have a snippet of code that is functioning correctly. I am wondering if it is possible to pass a pre-defined function as a parameter within express.post(). const exs = require('express'); const exs_r = exs.Router(); router.post('/click&a ...