Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory:

import Vuex from "vuex";

const createStore = () => {
    return new Vuex.Store({ 
      state: {
        forms : [],
      },
      mutations: {
        setForms(state, forms) {
          state.forms = forms
        }
      },
      actions: {
        setForms(vuexContext, forms) {
          vuexContext.commit("setForms", forms)
        }
      },
      getters: {
        getForms(state) {
          return state.forms
        }
      }
    })
}

export default createStore;

Now, when trying to fetch data and store it on a specific page:

  async fetch(context) {
    return axios.get(..)
      .then(data => {
          context.store.dispatch("example/setForms", data.data) 
      })
      .catch(e => {
        context.error(e);
      });

The above code results in the following error message:

unknown action type: example/setForms

What could be causing this issue?

Answer №1

You may want to make some adjustments to your example.js file for better functionality:

//store/example.js

export const state = () => ({
  forms: [],
});
export const mutations = {
  setForms(state, forms) {
    state.forms = forms;
  },
};
export const actions = {
  setForms(vuexContext, forms) {
    vuexContext.commit("setForms", forms);
  },
};
export const getters = {
  getForms(state) {
    return state.forms;
  },
};

Here's an example of how you can use it:


fetch() {
    return axios
      .get(...)
      .then((data) => {
        this.$store.dispatch("example/setForms", data.data);
      })
      .catch((e) => {
        context.error(e);
      });
  },

Answer №2

Make sure to include namespaced: true in your store configuration like this:

const moduleA = { 
      namespaced: true,
      state: {
        forms : [],
      },
      mutations: {
        setForms(state, forms) {
          state.forms = forms
        }
      },
      actions: {
        setForms(vuexContext, forms) {
          vuexContext.commit("setForms", forms)
        }
      },
      getters: {
        getForms(state) {
          return state.forms
        }
      }
}


const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
});


export default store;

This enables you to call it using

$this.store.commit("a/setForms");

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

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

Is it normal for Node's console to not display all object properties?

After running some code, I noticed something peculiar. console.log(myURL); It seems that the extension property is missing: console.log(myURL.extension); However, when logging it on its own, the value appears correctly. The URL object was created ...

In CodeIgniter, the $this->input->post() function consistently returns an empty value

I'm encountering an issue where the value from an AJAX post always turns out empty. Even after confirming that the value is correct before the post, I'm unable to retrieve it using $this->input->post() HTML <?php if ($product_info->stock ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Issues encountered with AngularJs filter search functionality

Why am I having trouble adapting this search filter from here? This is what my code looks like: controllers.js angular.module('starter.controllers', ['starter.services']) .controller('AppCtrl', function($scope, $ionicModal ...

Employing state management in React to toggle the sidebar

A working example of a sidebar that can be toggled to open/close using CSS, HTML and JavaScript is available. Link to the Example The goal is to convert this example to React by utilizing states instead of adding/removing CSS classes. To ensure the side ...

Effortlessly implement CSS styling in a scoped shadow element with Vue3

I am facing an issue with applying styles to an anchor element in my code. Below is a snippet of the code: <template> <custom-button> #shadow-root (open) <a href="#"></a> <other-custom></other-c ...

Anticipated outcome for absent callbacks in module API implementation

I am seeking advice on the expected behavior when developing a Node module API. It is becoming complicated in my module implementation to check if the caller has provided a callback before calling it. I am starting to believe that it may be the user's ...

Change the background color of all cells in a Bootstrap table by hovering over a single cell

Here is the code for a bootstrap table: <body leftmargin="0" topmargin="0" bgcolor="#ffffff" marginheight="0" marginwidth="0"> <div class="container-fluid h-100"> <div class="row float-right align-items-center" style="height: 5%;"> ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

I could really use some assistance with the concept of "AJAX" - can anyone help

After spending several months working with AJAX, I have come to understand the typical request lifecycle: Sending parameters to a background page (PHP/ASP/HTML/TXT/XML ... what other options are available?) Performing server-side processing Receiv ...

Unexpected behavior observed in component due to Vuex store

When attempting to access the store data in a component embedded directly in the HTML, you can use the following syntax: {{$store.state.notificationArea.cart.total;}} This method works properly. However, if trying to access the same data in the computed ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

Vue JS - Show the second option in the select menu once the first option is disabled

Can anyone assist me with displaying the second option in a select drop-down menu after the menu is disabled? The select menu will be disabled if there are only two options available. However, instead of showing the default 'Select nationality' ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...