How can I refactor this vuex Mutation?

Asked

Viewed 57 times

3

I have the following scenario: I’m manipulating the object namespaced questions, within it exists list and news, want to create a mutation that adds a key value pair in questions within those two arrays.

I want a generic function that knows which of the two arrays is, and changes that specific Question.

const SET_TYPING_COMMENT = (state, question) => {
    state.list = [
        ...state.list.map(_question => {
            if (_question.id == question.id) {
                _question = { ..._question, typing: true };
            }
            return _question;
        })
    ];

    state.news = [
        ...state.news.map(_question => {
            if (_question.id == question.id) {
                _question = { ..._question, typing: true };
            }
            return _question;
        })
    ];
};

1 answer

4


You can do it like this:

const changeQuestionState = (state, type, {id}, typing) => {
  return state[type].map(_question => {
    return { 
      ..._question, 
      typing: _question.id == id ? Boolean(typing): _question.typing
    };
  });
}

const SET_TYPING_COMMENT = (state, question) => {
  ['list', 'news'].forEach(type => {
    state[type] = changeQuestionState(state, type, question, true);
  });
};

The idea is to create a function that takes everything it needs to return the array with the new state. You can also do the state.list = drier with ['list', 'news'].forEach(type => {

Note: When you use the .map() you don’t need the operator spread, the .map() does not change the original array.


If you want to put this new function inside the action you don’t need so many arguments...

const SET_TYPING_COMMENT = (state, question) => {
  ['list', 'news'].forEach(type => {
    state[type] = state[type].map(_question => {
      return {
        ..._question,
        typing: _question.id == question.id ? Boolean(typing) : _question.typing
      };
    });
  });
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.