Creating real-time updates in Vuex and components using their data

There are two distinct elements here - a button and a form. By clicking the button, I can trigger an action in Vuex using "$store.dispatch".

addWorkerSubmit: async function () {
      ...
      await this.$store.dispatch('workermanage/addWorkerSubmit', formData)
    }

In Vuex, there is a function that sends a backend request to add data into the database.

const actions = {
  ...
  async addWorkerSubmit ({ commit }, formData) {
    let { status, data: { code, msg } } = await axios.post(`/manager/worker_manage/addStaff`, formData, {
      headers: { 'content-type': 'multipart/form-data' }
    })
    if (status === 200 & code === 0) {
      ...
    }
  }
}

However, after inserting new data into the database, the form component does not automatically update with this new data. Only by refreshing the web page does the table reflect the added data.

<Table
        border
        height="700"
        :columns="peopleColumns"
        :data="persons"
      >
        ...
   </Table>
...mapState({ persons: state => state.workermanage.staff.staff })

Upon checking, I noticed that only the original data appears in "state.workermanage.staff.staff" until the web page is refreshed.

The data stored in "state.workermanage.staff.staff" is acquired through the "nuxtServerInit" function from the database.

actions: {
      async nuxtServerInit ({ commit }, { req, app }) {
        let { status, data: { code, result } } = await app.$axios.get('/manager/worker_manage/getStaff')
        commit('workermanage/setStaff'...
    }

What steps should I take to ensure real-time updates for both the data in the table and "state.workermanage.staff.staff"? Thank you!

Answer №1

Perform a mutation called "workermanage/addStaff" within the addWorkerSubmit action. Is it possible for the backend to provide the added staff data upon submission?

const actions = {
  ...
  async addWorkerSubmit ({ commit }, formData) {
    let { status, data: { code, msg, staff } } = await axios.post(`/manager/worker_manage/addStaff`, formData, {
      headers: { 'content-type': 'multipart/form-data' }
    })
    if (status === 200 && code === 0) {
      commit('workermanage/addStaff', staff)
    }
  }
}

const mutations = {
    addStaff(state, payload) {
        state.staffs.push(payload)
    }
}

If the backend does not return the added staff, you can either query the updated list (similar to nuxtServerInit action) or retrieve the added staff from the formData.

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

Troubleshooting Nuxtjs configuration issue with setting up Github Pages

Trying to set up Github Pages deployment for NuxtJS but facing issues with the configuration file. I followed the documentation, but still can't get it right. The documentation suggests adding this code snippet in the file, which I tried multiple tim ...

Is it possible to list bash/sh files as dependencies in package.json?

Currently, I have a bash script named publish.sh that I use for publishing modules to npm. Since I am constantly adjusting this script, I find myself needing to update every copy of it in each npm module I manage. Is there a method to include this bash sc ...

Step-by-step guide on deploying a Nuxt SSR application to AWS Amplify using Git

I've been struggling to figure out how to successfully deploy my Nuxt SSR app on AWS Amplify. The directory structure of my project is as follows: my-nuxt-app |-.nuxt(contains view, dist etc.) |-assets |-components |-layouts |-pages |-plugins |-static ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...

Utilizing replace and regex in jQuery to add a space before a capitalized character within a word

these are the elements in the array WorkNumber WorkType Version Status Module Priority AssignedBy AssignedTo Subject Details EstimatedTime ActualTime CreatedDate ModifiedDate i would like the ou ...

Unable to add an event while looping through a NodeList in JavaScript

Seeking assistance in iterating a NodeList object using javascript, and implementing a click event for each item : document.addEventListener("DOMContentLoaded", async () => { try { posts.map(post => { container.innerHTML += out ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Establish a seamless UDP connection using JavaScript and HTML5

Is it feasible to establish a direct two-way connection with a UDP server using javascript/HTML5 (without node.js)? While WebRTC is an option, my understanding is that it does not support sending datagrams to a specific server. I am primarily focused on c ...

PubNub's integration of WebRTC technology allows for seamless video streaming capabilities

I've been exploring the WebRTC sdk by PubNub and so far, everything has been smooth sailing. However, I'm facing a challenge when it comes to displaying video from a client on my screen. Following their documentation and tutorials, I have writte ...

Angular Bootstrap notifications will stay open indefinitely and will not automatically dismiss after a certain period

I need help with adding alerts using Angular Bootstrap that should dismiss themselves after a certain timeout. However, the alerts are not dismissing on their own. Here's the code snippet: angular.module('ui.services').service('AlertSe ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Utilizing conditional statements like if/else and for loops within a switch statement in JavaScript allows for

I am currently developing a request portal that involves dynamic checkboxes, labels, and textboxes that are dependent on an option list. As a beginner in javascript, I am facing challenges with creating conditional statements. I have managed to make progr ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

Arranging ng-grid by a hidden column

Imagine having an array of objects structured like this: { name: ... age: ... dept: ... } Now, if you want to display these objects in an ng-grid with only columns for name and age, you can set it up like this: columnDefs: [{field:'name' ...

Utilizing JSON compression techniques on both the client and server ends for more efficient data transfer

I'm searching for a tool that can compress JSON on the server side (using C#) and then decompress it on the client side, as well as vice versa. The entire data model for my webpage is in JSON format and I need to find a way to reduce its size. I' ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

Comparing XDomainRequest and XMLHTTPRequest - which one to choose

Our team is currently developing an application utilizing PixiJS that integrates a dynamic json loader. The .json files are loaded using the following logic: if(window.XDomainRequest) { this.ajaxRequest = new window.XDomainRequest(); } else if (windo ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Attempting to merge the data from two separate API responses into a single array of objects

I have a current project in which I'm dealing with an object that has three separate arrays of objects. Here's a glimpse of the structure... [ Array 1:[ { key: value} ], Array 2:[ { key: value}, { key: value} ], Array ...

Run a JavaScript function once the AJAX content has been successfully added to the element

I have a JavaScript AJAX function that retrieves content and adds it to an HTML element named content_holder. After the content is updated with the AJAX request, I want to trigger a function. I've attempted to include a <script> tag within the a ...