"Implementing Nested Actions in Vuex: A Guide on Calling Actions within Actions

I am currently working on a small Vue App with a Rails API where I am using Vue, Vue-Resource, and Vuex. I have successfully fetched all users from the database and now I am trying to update one of them. The patch operation for updating the user is working fine, but after running the updateUser action, I want to refresh the Vuex store by running the fetchUsers action again.

However, when I try to run fetchUsers inside the updateUser promise, I encounter the following error:

undefined:1 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined

This is how my vuex/actions.js file looks like:

export const fetchUsers = function ({ dispatch, state }) {
  this.$http.get('http://localhost:3000/api/v1/users').then((response) => {
    dispatch('SET_USERS', response.data)
  }, (response) => {
    dispatch('SET_USERS', [])
    console.log(response)
  })
}

export const updateUser = function ({ dispatch, state }, user) {
  this.$http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => {
    fetchUsers()
  }, (response) => {
    console.log(response)
  })
}

I understand that the fetchUsers action seems to lose context somehow, but I am unsure how to address this issue. Any assistance would be greatly appreciated!

Answer №1

this is the code snippet that resolved my issue :)

import Vue from 'vue'

export const fetchUsers = ({ dispatch, state }) => {
  Vue.http.get('http://localhost:3000/api/v1/users').then((response) => {
    dispatch('SET_USERS', response.data)
  }, (response) => {
    dispatch('SET_USERS', [])
    console.log(response)
  })
}

export const updateUser = ({ dispatch, state }, user) => {
  Vue.http.patch('http://localhost:3000/api/v1/users/' + user.id, {user: user}).then((response) => {
    fetchUsers({dispatch})
  }, (response) => {
    dispatch('SET_USERS', [])
    console.log(response)
  })
}

Answer №2

When you use console.log('this', this) within a store module, the dispatch method is visible in that particular context. This allows you to utilize it as follows:

// Inside of store/test.js module
export const state = () => ({
    test: 'somestate'
})

export const mutations = {
  ACTION_TWO(state, data) {
    state.test = data;
  }
}

export const actions = {
  actionOne({ commit }, value) {
     this.dispatch('test/actionTwo', value); // moduleName/action
  },
  actionTwo({ commit }, valueToCommit) {
    commit('ACTION_TWO', valueToCommit);
  }
}

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 absence of defined exports in TypeScript has presented a challenge, despite attempting various improvement methods

I've exhausted all available resources on the web regarding the TypeScript export issues, but none seem to resolve the problem. Watching a tutorial on YouTube, the presenter faced no such obstacles as I am encountering now. After updating the tsconf ...

Sending SQL queries with multiple selections, each containing three values for every option

I am faced with a challenging question that will require me to dedicate long hours towards solving it and finding a solution. Imagine I have a multiple select element with various options, each consisting of 3 values: One value for the language name One ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

Executing a POST request with AJAX in jQuery to communicate across different domains and fetching XML data as

Is it possible to send an AJAX request using the POST method and receive XML as a response text? If so, please provide me with the steps to achieve this. For example: url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate" data ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

A guide to successfully interacting with multiple elements simultaneously at a single spot

Within my graphic chart, I have various dots that may be located in the same spot. I am looking for a way to handle clicks on two or more elements simultaneously in Vue 3. Do you know of any straightforward methods to achieve this? I attempted using refs ...

If the if logic in Express.js fails to function properly, it will consistently output the same message

Every time I run this code, it always displays the same message, even when I input different email addresses let message = ""; const findQuery = "select email from Users where email = ?"; const queryResult = await db.query(findQue ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

What is the reason for the absence of the $.ajax function in the jQuery package designed for node.js?

Here is my code sample, which I would like to use for practicing with jQuery's ajax function. Note that I have already installed the jQuery package using npm install jquery: var $ = require('jquery'); var remoteValue = false; var doSometh ...

Mixing box-shadow and blur filters can result in unusual artifacts appearing in Webkit browsers

Recently, I encountered an intriguing and frustrating bug in WebKit browsers. Consider a scenario where there is a parent DIV (let's say .wrapper) and a child DIV (.main). You apply a box-shadow on the .main DIV and a blur filter on the .wrapper DIV. ...

Leverage AJAX to fetch data from the database

I've been exploring different methods to automate the process of copying a database table. While replication was suggested as an option, I found it challenging to set up properly. Therefore, I have decided to use a script approach instead. In an effo ...

Accessing a jstl variable within javascript script

I need to access a JSTL variable within a JavaScript function. The JavaScript code submits a form. $("#userSubmit").on('submit', function () { document.getElementById("userForm").submit(); }); In the server-side code - request.setAttribu ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message. I found a solu ...