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

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

Display a loader in Vue JS at the start and then remove it once the response is received

To achieve the functionality of showing a loader initially and hiding it after receiving a response, you can use the following code: <template> <div id="app"> <Document :loading="loading"> </div> </tem ...

Include a sub-component N times within the main component, depending on the current state value

I need assistance in adding a child component called ColorBox to the parent component named ColorBoxContainer based on the value stored in state as noOfBoxes: 16. I've tried using a for-loop but it seems like my code is incorrect. Can someone guide me ...

The React-Virtualized Autosizer component is returning a height value of 0 when used with VirtualScroll

Despite AutoSizer's width providing the correct value, I am consistently encountering a height of 0 for Autosizer. This is causing the VirtualScroll component to not display properly. However, when using the disableHeight prop and setting a fixed heig ...

AngularJS dropdown menu for input selection binding

Hey there, I need some help with the code below: <input type="text" class="form-controlb" ng-model="item.name" id="name" placeholder="Enter Name" /> Also, I have a dropdown as shown here: <div class="col-sm-12" ng-model="query"> ...

npm ERR! Your operating system has denied the operation

When attempting to install create-react-app globally using 'npm install -g create-react-app', an error occurred due to insufficient write access to the /usr/local/lib/node_modules directory. The error message displayed was as follows ...

Encountering numerous errors when attempting to incorporate lottie-web into my JavaScript file

I am in the process of creating a unique audio player for my website utilizing HTML, CSS, and JavaScript. I encountered some challenges while trying to get it to work effectively on Codepen as well as my text editor. The animations were not functioning pro ...

Developing custom functions in ejs for individual posts

In my blog, I have a feed where all users' posts are displayed dynamically using ejs. There is a comment section that remains hidden until the user clicks the comments button. Below is a snippet of my ejs file: <% posts.forEach(post => { %> ...

The FlatList component will only trigger a re-render once the list has been scrolled

I need help with updating a FlatList in my app. Currently, the list is populated by an array stored in the component's state and can be filtered using a filtering function that updates the state with a new filtered array. However, I have noticed that ...

Creating a client-server application in JavaScript with the npm-net module

In my possession is a straightforward piece of code titled echo_server.js. It serves as a server that simply echoes back any text received from the connected client. var net=require('net'); var server=net.createServer(function (socket) { socke ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

I am currently studying react.js and struggling to comprehend how the deployment process for a react app functions

Will the server only serve the index.html file or is there a way for the client to run that html file as it's not a regular html file? Do I need a backend node to make it work? I'm having trouble understanding the entire process. Normally, a cli ...

Tips for sorting through JSON Data to isolate a particular day

I developed a Food-App that displays a different menu every day. I retrieve the local JSON Data using Axios and attempt to filter the mapped menu with .filter. My issue lies in not being able to filter specific days. I attempted to restructure the JSON Da ...

All the GET request methods are functional except for the final one. I wonder if I made a mistake somewhere?

After examining all the GET request methods, it appears that only the last one is not functioning properly. Despite attempting to log something to the console, no output is being displayed. router.get('/', function(req, res) { Golf.find({Year: ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

Using array map to create a centered table in a React web application

In my React project, I created a table using the array.map function. However, I'm facing an issue where the output of array.map is always aligned to the left, even before the table itself. I want to center the entire table. JSX: <div className=&qu ...

Is it possible for a table row's cell to determine the value of the cell in the row above it?

Let me illustrate my issue with an example. Consider the following table: <table> <tr> <th>First</th><th>Second</th><th>Third</th> </tr> <tr> <td>A</td><t ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

Guide to rendering pages in SSR mode in NextJS on a specific environment and serving static pages on a different environment

I am facing a challenge with my setup where I have a Strapi backend deployed on the environment I manage, and a NextJS frontend hosted on Vercel. On the other hand, my client has the same Strapi backend code running on Google Cloud and the frontend code ho ...