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

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Communication between AngularJS directives and controllers occur when a function is called upon a change

I have developed a unique custom directive which is defined as: <div class="col-md-6"> {{templateMapping[colProp].SheetPointer}} <select class="form-control" ng-model="selectedColumn" ng-change="changeMapping()" ng ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

What is the best way to recycle a component instance in Nuxt.js?

Recently, I developed a cutting-edge single-page application using Nuxt.js 2 and Vue2. The highlight of this app is a complex WebGL visualizer showcasing a 3D scene across two distinct sections: SectionDesign and SectionConfirm <template> <Sec ...

Manipulate state in parent component from child component using onClick function with React hooks

Hello, I am facing a challenge trying to store data from a modal (child function) within the main (parent) function. Depending on which button is clicked, the modal loads specific HTML content (all buttons perform the same action). export default function ...

Automated library that refreshes the webpage instantly upon any server modifications

Seeking a Javascript solution to automatically refresh a webpage when the server version is updated. Update: I am aware of the technical aspects involved and how to implement this feature. However, I am interested in finding an existing solution that I ca ...

Sending a JavaScript object as a prop in a React component

Currently, I am enrolled in a React course that requires us to pass a single JavaScript object as props to a React application. Here's the code snippet I have been working on: import React from 'react'; import ReactDOM from 'react-dom& ...

Using Phoenix Channels and Sockets in an Angular 2 application: A comprehensive guide

My backend is built with Elixir / Phoenix and my frontend is built with Angular 2 (Typescript, Brunch.io for building, ES6). I'm eager to start using Phoenix Channels but I'm struggling to integrate the Phoenix Javascript Client into my frontend. ...

How to manage ajax URLs across multiple pages?

I have my website set up at http://example.com/foo/ within a directory, separate from the main domain. Through the use of .htaccess, I've configured the URLs to appear as http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com ...

Is there a way to use JavaScript or jQuery to automatically convert HTML/CSS files into PDF documents?

While using OS X, I noticed that in Chrome I have the option to Save as PDF in the print window by setting the destination to "Save as PDF". Is this feature available on Windows? Is there a way to easily save to PDF with just one click? How can I access t ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

Error: Unable to submit data as the function this.submitData is not recognized

Having trouble calling an async function in the mounted() lifecycle hook of Vue.js? Keep getting the error message: Uncaught TypeError: this.submitData is not a function. Here's the code snippet in question: <template> <section class=&quo ...

Creating files using the constructor in Internet Explorer and Safari

Unfortunately, the File() constructor is not supported in IE and Safari. You can check on CanIUse for more information. I'm wondering if there's a workaround for this limitation in Angular/JavaScript? var file = new File(byteArrays, tempfilenam ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

The document inside the database is displayed in italicized text when it is stored in Firebase

try { // establish a new collection named 'pactLists' const pactListsCollection = collection(db, "pactLists"); // used for storing records of created pacts by users. // generate a unique id for the pact and set it as the invite c ...

Utilizing Electron to save editable user data in a .txt file

I am making an electron app that converts data from .txt files to Javascript arrays. This data is stored inside a folder called faces in the main directory. I also have a button in my app which, when clicked opens file explorer at the faces folder so the u ...

How can I iterate through a directory containing files and extract the exported JavaScript object from each one?

In my current project using nodejs / nextjs, I have file system access and a folder containing multiple React files: content - blog-post-1.jsx - blog-post-2.jsx - blog-post-3.jsx The task at hand is to extract the frontmatter from each file. My init ...

Java Selenium Javascript executor fails to return desired result

Attempting to execute a javascript function I created to gather all comments from an HTML site using xpath (requirement). The function, when pasted directly into a browser without the 'return' statement, works flawlessly. However, when run th ...