mercredi 22 mai 2019

What are the pros and cons of using a single action to modify multiple values, or an action for each value? Why?

I'm trying to find what would be the best pattern to manage my reducers.

I have the following page:

Set of fields

I know I could've used redux-forms for this, but this is not the point since I only used these fields/form as an example.

We have multiple ways of handling this on redux:

  • 1: having a single action to update those fields values based on the input's name property:
const UPDATE_VALUES = 'UPDATE_VALUES';

const INITIAL_STATE = {
  aString: '',
  setOfValues1: [],
  setOfValues2: []
};

const reducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case UPDATE_VALUES: {
      if (action.name === 'setOfValues1' || action.name === 'setOfValues2') {
        const array = [...state[action.name]];
        array.push(action.value);
        return {
          ...state,
          [action.name]: array
        };
      }

      return {
        ...state,
        [action.name]: action.value
      };
    }
    default:
      return state;
  }
};

  • 2: having multiple actions to each field value:
const UPDATE_A_STRING = 'UPDATE_A_STRING';
const UPDATE_SET_1 = 'UPDATE_SET_1';
const UPDATE_SET_2 = 'UPDATE_SET_2';

const INITIAL_STATE = {
  aString: '',
  setOfValues1: [],
  setOfValues2: []
};

const reducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case UPDATE_A_STRING:
      return {
        ...state,
        aString: action.value
      };
    case UPDATE_SET_1: {
      const array = [...state.setOfValues1];
      array.push(action.value);
      return {
        ...state,
        setOfValues1: array
      };
    }
    case UPDATE_SET_2: {
      const array = [...state.setOfValues2];
      array.push(action.value);
      return {
        ...state,
        setOfValues2: array
      };
    }
    default:
      return state;
  }
};

  • and more ways that I'm not aware of.

what would be the good practice/best pattern in this case? Where can I look for, to learn more patterns to situations like these and other situations as well?

Aucun commentaire:

Enregistrer un commentaire