Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management.

For CRUD operations on the data, I have implemented Axios.

The issue arises when, for example...

I make a POST request to my MongoDB database through an Express server.

Even though both are temporary placeholders which will be replaced later, the state in Vuex does not update and the component fails to auto rerender with the new data. A page refresh becomes necessary.

While I can manually re-render a component using mutations on the state as shown in the example below, this approach is not ideal or preferred by me.

Is there a way to prompt updates to the state to automatically trigger a rerender of the component when performing post/delete/update actions? I am not interested in hard refreshes or placing fetchData() inside the updated() lifecycle hook, since the component is constantly polling for fresh data every 100ms.

The code snippet below is not mine, but it perfectly illustrates what I am aiming for:

// Tasks module
import axios from 'axios';

const resource_uri = "http://localhost:3000/task/";

const state = {
    tasks: []
};

const getters = {
    allTasks: state => state.tasks
};

const actions = {
    async fetchTasks({ commit }) {
        const response = await axios.get(resource_uri);    
        commit('setTasks', response.data);
    },
    async addTask( { commit }, task) {
        const response = await axios.post(resource_uri, task);
        commit('newTask', response.data);
    },
    async updateTask( { commit }, task) {
        const response = await axios.put(`${resource_uri}${task.id}`, task);
        commit('updTask', response.data);
    },
    async removeTask( { commit }, task) {
        const response = await axios.delete(`${resource_uri}${task.id}`);
        commit('deleteTask', task);
    }
};

const mutations = {
    setTasks: (state, tasks) => state.tasks = tasks,
    newTask: (state, task) => state.tasks.unshift(task),
    updTask: (state, updatedTask) => {
        const index = state.tasks.findIndex(t => t.id === updatedTask.id);
        if(index !== -1) {
            state.tasks.splice(index, 1, updatedTask);
        }        
    },
    deleteTask: (state, task) => state.tasks = state.tasks.filter(t => task.id !== t.id),
};

export default {
    state, getters, actions, mutations
}

Edit: Current workflow looks like this:

  • axios.get(task)
  • Commit and save data in state.tasks[]
  • When axios.post(data) is called, the server receives the data but the state.tasks[] remains unchanged, causing the component to not re-render with the new data.

How can I trigger a component re-render when data has been saved in the database without directly modifying state.tasks[] using array methods?

Answer №1

When reviewing your code, it appears that the reason why you are not receiving refreshed data in your component is due to incorrect mutations implementation. Below is the problematic code:

 const mutations = {
    setTasks: (state, tasks) => state.tasks = tasks,
    newTask: (state, task) => state.tasks = [task, ...state.tasks],
    updTask: (state, updatedTask) => {
        let tasks = [...state.tasks];
        const index = tasks.findIndex(t => t.id === updatedTask.id);
        if(index !== -1) {
            tasks.splice(index, 1, updatedTask);
        }
        state.tasks = [...tasks];
    },
    // deleteTask should work correctly
    deleteTask: (state, task) => state.tasks = state.tasks.filter(t => task.id !== t.id),
};

Update

In response to your comments about potentially having more complex data structures with nested arrays and other complexities, I recommend shifting the logic to the server side. All operations such as update, push, delete should be handled on the server, which will then return the updated tasks. This approach eliminates the need for multiple mutations and simplifies the process down to just one mutation: setTasks.

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

The words are scrawled on the pages, far away from the

https://i.stack.imgur.com/Pg5sq.png A new employee monitoring project has been initiated, with the first interface being the login page. Upon clicking the registration button, users are required to verify the email sent to them. However, there seems to ...

Jquery issue: Lightbox unexpectedly closing by itself :(

Help needed: My light box is closing automatically within seconds. $(document).ready(function(){ $('.lightbox').click(function(){ $('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear'); ...

Preventing a JavaScript timer function from executing multiple times when triggered by an 'in viewport' function

I am trying to create a website feature where a timer starts counting up once a specific div is scrolled into view. However, I am encountering an issue where scrolling away restarts the timer, and I would like the final value that the timer reaches to rema ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

Unable to access the done property in an AJAX JSON promise

Trying to dive into the world of JavaScript promises. My goal is to create a button that triggers a function displaying the result of a promise from another function. So far, I've been following tutorials and here's where I'm at: function my ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Difficulty encountered while using CSS to customize a vue template

I'm currently working on a login page and experiencing difficulty styling Vue templates using CSS. Here is the code that works without Vue: HTML <body class="text-center"> <form class="form-signin"> <h1 class="h3 mb-3 fon ...

Error rendering {message} object on the Chrome Console

In my ReactJS component, I am utilizing the {message} parameter from props. Check out the code snippet below: import React from "react"; const MyMessage = ({ message }) => { if (message?.attachments?.length > 0) { return ( < ...

Encountering issues with npm installation on a Linux operating system

Embarking on a new journey learning Vue.js, I find myself in unchartered territory with Node.js. Initially, when I cloned the repository for my course and followed the setup instructions, everything ran smoothly without any issues. However, a blunder on my ...

Encountering an issue with connecting nodejs to mqlight

I have been working with nodejs and mqlight to test out some sample code provided on https://www.npmjs.com/package/mqlight. My current setup consists of nodejs 5.5.0 and npm version 3.3.12. To install mqlight, I used the command npm install mqlight. ...

"My JavaScript code for toggling visibility is not functioning properly. Any suggestions on how to fix

I am currently working on a task that involves showing and hiding container1, but I am confused as to why my code is not functioning properly. The task requirements are as follows: - Clicking on the "Show" button should display container1 - Clicking on the ...

`AngularJS Integration in Liferay`

Utilizing AngularJS globally within Liferay Portal is a strategy I would employ. The flexibility of AngularJS allows for dynamic views in web applications, enhancing the readability and development speed of the environment. I prefer leveraging the declara ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Direct your attention to alternative data sources following the selection of an item in the typeahead search feature

Having some trouble with angular-ui bootstrap: I am using 2 input elements: <input type="text" ng-model="selected" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" typeahead-on-select="focusSuccessive($item, $model, $label, $ev ...

Leveraging require in AWS lambda operations

As part of my exploration into AWS Lambda functions, I've been trying to determine if the require statement can be used within them. This would allow me to incorporate other non-lambda functions into my code. Although zipping the node modules folder i ...

The ng-click function ceases to trigger after the $location dependency is included in the controller

I need some help with running a ng-click function from my controller. The strange thing is, when I don't use the $location dependency, the ng-click function works fine. But as soon as I add $location to the controller, the ng-click function stops work ...

Primeng - Concealed dropdown values within a scrollable table header

Recently, I integrated Primeng p-table with a filter and frozen column feature (with one column being fixed while the others are movable). However, I encountered an issue with the select dropdown in the header. When I try to open the dropdown, the values a ...