2

I have broken my actions into multiple files to make my project more maintainable and extensible. Trying to dispatch from one action to another, however, is not working.

My file tree looks like this:

store.js
actions
  |--actions.js
  |--createShape.js
  |--addShape.js

My store.js looks like:

import actions from './actions/actions'

const PlaypadStore = {
  namespaced: true,
  state: {
    localState: ''
  },
  actions: {
   ...actions,
  },
}

My actions.js folder has the following:

import CREATE_SHAPE from './createShape';
import ADD_SHAPE from './addShape';

export default {
  CREATE_SHAPE,
  ADD_SHAPE,
}

The problem is trying to dispatch ADD_SHAPE from CREATE_SHAPE. My createShape.js looks like the following:

const CREATE_SHAPE = ({ state, dispatch }) => {
  return dispatch('ADD_SHAPE')
}

export default CREATE_SHAPE;

But it returns me this:

[vuex] unknown local action type

The question is this: how can I break my actions into multiple files, but still be able to dispatch actions from one to another?

Modermo
  • 1,852
  • 2
  • 25
  • 46

2 Answers2

4

if you use 'export default...' in your action-files and import your files in the store like that:

import actions_one from './actions_one';
import actions_two from './actions_two';

you can then use the spread operator to make it like you're importing one object:

export default new Vuex.Store({
  namespaced: true,
  actions: {
    ...actions_one,
    ...actions_two
  },
...
Dharman
  • 30,962
  • 25
  • 85
  • 135
OnFire
  • 129
  • 5
0

you need to let Vuex know that actions.js, createShape.jsand addShape.jsare "modules" of your store for this to work. You can read more about it in the Vuex Modules documentation.

Basically you need an index.js file declaring the modules at the root of your store. That should look like this:

import actions from "./actions";
import createShape from "./createShape";
import addShape from "./addShape";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    actions,
    createShape,
    addShape
  }
});

At this point your dispatch call should work, UNLESS it comes from another vuex store module, in that case just specify "root = true" as they pointed out here.

dnhyde
  • 1,265
  • 2
  • 14
  • 24
  • 2
    I want `createShape` and `addShape` to be imported in `actions`. – Modermo Mar 31 '19 at 22:36
  • If they are two vuex store modules already you should call dispatch with the "root=true" option. There should be no need to import an action A from module A into module B. If this is your need and not to dispatch that action A, maybe that action A should belong to module B. – dnhyde Mar 31 '19 at 22:41
  • 1
    Importing from one module into another isn't what I'm trying to. They are both contained within the same module. – Modermo Mar 31 '19 at 22:44
  • Does it work if you dispatch with the "root=true"? That is in your createShape.js you use: `return dispatch('ADD_SHAPE' , {root:true})` – dnhyde Mar 31 '19 at 23:15