Sending information from a Vuex module to a component following an axios request

I'm currently working on developing a Vue.js based application. Here's the scenario I'm facing: I have a component with a popup where users can create an 'expense' entry. Upon clicking the 'save' button, a function in the Vuex module is called to handle the API request for saving the entry. It looks something like this:

import { mapActions } from 'vuex';

export default {
    name : 'CreateExpense',
    data(){
        return {
            expense : {
                expense : null,
                amount : 0,
                comment : null
            }
        }
    },
    methods : {
        ...mapActions(['addExpense']),
        saveExpense(){
            this.addExpense( this.expense );
        }
    }
}

In my Vuex module, I have defined the following actions:

const actions = {
    addExpense({commit},expense){
        axios.post( env.API_URL + 'save-expense',expense)
        .then( response => commit('addExpense',expense) )        
    }
}; 

My issue lies in determining how to inform the component that the API call has been completed and the expense state object has been updated. This information is needed so that the component can then close the popup that was opened. Ideally, I would like the handling of .catch/.then functions to be done within the module itself, while the component focuses on closing the popup and displaying an alert message. Could someone please provide some guidance or direction on how to achieve this?

Answer №1

Utilize the mapGetters method


import { mapActions, mapGetters } from 'vuex';

export default {
    name : 'CreateExpense',
    data(){
        return {
            expense : {
                expense : null,
                amount : 0,
                comment : null
            }
        }
    },
    methods : {
        ...mapActions(['addExpense']),
        saveExpense(){
            this.addExpense( this.expense );
        }
    },
    computed: {
        ...mapGetters(['expense'])
    },
    watch: {
      expense (val) {
        if (val) //close popup modal
      }
    }
}

store.js

export default new Vuex.Store({
  actions: { ... },
  state: { ... },
  getters: {
    expense: ({expense}) => expense
  }
}

Answer №2

Alternatively (without using mapGetters)

In the Vuex store module:

addExpense ({commit}, expense) {
  return new Promise ((resolve, reject) => {
    axios.post(env.API_URL + 'save-expense', expense)
    .then(response => {
      commit('addExpense', expense);
      resolve(response); // This will be returned to the component
    })
    .catch(err => {
      reject(err);
    })
  })
}

And in your Vue.js component:

mounted: function () {
  this.myMethod()
},

methods: {
  myMethod: function () {
    this.$store.dispatch('addExpense')
    .then(response => {
      console.log('response', response) // We should receive value from the resolve
    }) 
  }
}

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

Acquire key for object generated post push operation (using Angular with Firebase)

I'm running into some difficulties grasping the ins and outs of utilizing Firebase. I crafted a function to upload some data into my firebase database. My main concern is obtaining the Key that is generated after I successfully push the data into the ...

Restoring the position of the <Rect/> element after dragging in a React + Konva application

In my attempt to make a Rect component snap back to its original position using ReactKonva, I defined a Toolbar class with certain dimensions and initial positions for the rectangle. However, after dragging the rectangle and attempting to reset its positio ...

What is the best way to return JSON data in a compressed (gzip) format to an Ajax Request using Java?

When sending compressed JSON in response to an Ajax request from my Java program, I understand that I need to set the Content-Encoding in the Response Header to gzip. However, are there any additional steps I should take? ...

What is the method for adding 24 hours to a 12-hour timestamp while preserving the AM and PM designation?

I have created the following code to display real-time, but I am struggling with adding a timestamp that switches from 24-hour format to 12-hour format with AM and PM. setInterval(function() { var date = new Date(); var hours = date.getHours(); va ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

Error encountered: WebGL Type error in Three.js

Currently working on a small music visualizer project using WebGL and Three.js with the help of the ThreeAudio.js library. Everything seems to be running smoothly, but I've encountered an error that I'm keen on resolving: "Uncaught Type Error: T ...

Can you specify the third argument sent to the listener?

Recently I delved into exploring the capabilities of the d3 framework. One thing that caught my attention was the presence of a third parameter in the event listener for v3. Despite always being 0, I couldn't find any explanation on its intended purpo ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Key to Perform Right Click

Hey, I could use a little advice window.addEventListener('keyup', function (event) { if (document.activeElement && document.activeElement.tagName === 'INPUT') { return; } switch (String.fromCharCode(event.keyCode ...

What is the process for utilizing datePipe in an Angular component?

How can I implement DatePipe in my Angular component? This is the code snippet that I am currently using. for (let i = 0; i < this.days.length; i++) { this.storeStart(this.days[i], null, null, null); } I have stored weekdays (Monday to Frid ...

Using Google Maps to trace a line showing the distance traveled

I want to create a 'distance traveled' polyline along a set route using V3 of the Google Maps API. The polyline should pass through multiple waypoints/legs. Currently, I am using the DirectionsService to draw the entire route. In addition, I a ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Nested JSON array is being shown as [Object Object] within a TextField

I am facing an issue with mapping two sets of JSON data, which I will refer to as Set 1 and Set 2. In Set 1, the data (named sizingData) is being mapped to text fields using the following function: const fillTextField = () => { let result = []; ...

Using Plupload plugin to handle file uploads triggers unexpected page refresh when making Ajax requests

I have implemented the Plupload plugin to facilitate the uploading of multiple files. I have linked the FileUploaded event to the uploader in order to execute additional actions once a file has been uploaded. Below is where I am attaching the event. uploa ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

Issue with kendo grid not properly saving recently added data

Unexpected Grid Behavior: Adding a new record Pressing the update button in the grid for the newly added row Cancelling before saving After completing the above actions, the newly added row disappears. View js fiddle example <!DOCTYPE html> <h ...

Encountering a webpack mix issue on Ubuntu version 18

Whenever I try to execute the command ( npm run watch ), I encounter this error: @ development /home/nader/Desktop/asd/blog cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setu ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

How to retrieve the initial element of a specific tag using jQuery

As I am transitioning from standard JavaScript to jQuery in order to achieve cross browser compatibility, I am seeking guidance on how to rewrite certain functions in jQuery. Specifically, I am looking for the correct way to find the first element using jQ ...