Search code examples
vue.jsvuex

Use getter in the same module in which it was created


Is it possible to initialize state's property using getter which was created in the same module? Something like this:

export const gamesModule = {
state: {
    games: [],
    selectedGameID: null,
    playerOnTurnID: this.getters.getSelectedGame.playerData[0]
},
getters: {
    getGames: state => state.games,
    getselectedGameID: state => state.selectedGameID,
    getSelectedGame: state => getSelectedGameById(state.games, state.selectedGameID),
},
mutations: {
  SET_GAMES (state, game) {
    state.games.push(game);
  },
  SET_SELECTED_GAME_ID (state, id) {
    state.selectedGameID = id;
  },
  SET_PLAYER_ON_TURN_ID (state, playerID) {
    state.playerOnTurnID = playerID;
  }
},
actions: {
  async createGame({ commit }) {
    try {
      const { data } = await gameService.createGame();
      commit('SET_GAMES', data);
    } catch (error) {
      console.warn('Error creating new game: ', error);
    }
  },
  setSelectedGameID({ commit }, id) {
    commit('SET_SELECTED_GAME_ID', id);
  },
};

Written like this, it does not work because getters are undefined.


Solution

  • this does not exist in an object's context, and is only really applicable in constructor functions or classes.

    I see two problems here.

    First of all, you can't reference the object itself, because it hasn't been defined yet. You would have to create a local variable before declaring the object that would have the common property, in this case, the getter function.

    Second of all, more importantly, I'm not sure it would help to access the getter (Reducer) function, as it has no knowledge of the state, which is passed to it as the first parameter by the underlying Vuex library when processing mutations (Actions).

    Vuex is based upon the Redux pattern, Action -> Reducer -> Store, I would recommend reading it a quick introduction on how Redux works, as it will help you understand a lot better the action flow inside of Vuex.