call mutation from another module action

1.2k Views Asked by At

I am currently playing with vuex to start with after getting to know bit more of vue. So I started another todo with veux

I am able to add an item of todo after clicking add, but I do want to clear the input after it's done though. I am having two store modules.

One named todo_inputs another one is todos so when add is clicked addItem action is being called from todos module which does a commit setTodos

After the commit is done, I want to clear the input of the state in todo_input but somehow I can't reach it.

I read a few stackoverflow and also vuex documentation of https://vuex.vuejs.org/guide/modules.html#accessing-global-assets-in-namespaced-modules

Lots were saying something of using namespace such as `commit('todo_input/setInputText', null { root: true }) But this does not work though...

Also, if inside the modules if I put in {namespace: true} pretty much my other actions would break after this is set.

these are my store modules

todo_input.js

const state = {
  item: null
};

const getters = {
  getInputText: ({ item }) => item
};

const actions = {
  onInput({ commit }, e) {
    commit("setInputText", e.target.value);
  }
};

const mutations = {
  setInputText: (state, item) => {
    state.item = item;
  }
};

export default {
  namespaced: true, // I tried adding this here which breaks my other action such as onInput()
  state,
  getters,
  actions,
  mutations
};

todos.js

import api from "../../api/todo";

const state = {
  items: []
};

const getters = {
  itemList: ({ items }) => items
};

const actions = {
  // get list of todos
  fetchItems: async ({ commit }) => {
    try {
      const response = await api.fetch();
      commit("setTodos", response.data.data);
    } catch (e) {
      console.log(e, "error in fetchTodos in actions");
    }
  },
  addItem: async ({ commit, rootState }) => {
    try {
      const { item } = rootState.todo_input;
      if (!item) return;

      const response = await api.create(item);
      const newTodoList = [...rootState.todos.items, response.data.data];
      commit("setTodos", newTodoList);
    } catch (e) {
      console.log(e, "error in add item in actions");
    }
  }

};

const mutations = {
  setTodos: (state, todos) => {
    state.items = todos;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

store/index.js

import Vue from "vue";
import Vuex from "vuex";
import todos from "./modules/todos";
import todo_input from "./modules/todo_input";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    todos,
    todo_input
  }
});

I read a few posts, lots were saying using namespace and it does look obvious though, what am I doing wrong here?

Thanks in advance for any help / suggestions.

0

There are 0 best solutions below