Reusable redux action - update a single value

I often find when using React and Redux, I need to update a specific value in my redux store and the only difference is the key and the value. For example: key: 'firstName', value: 'Harry'.


An example action might look like:

export function changeFirstName(newState) {
    return { type: 'FIRSTNAME', newState };
}


So if we now needed to add an action for 'lastName', you can see how we are duplicating more and more code which essentially does the same thing, updates one value in the store.

Instead of this I created a re-usable action which I can update a single value in the Redux store with... And its as many lines of code as the fixed 'changeFirstName' action I showed above.

export function changeSingleReduxValue(newState, propertyName) {
  return { type: 'SINGLE_REDUX_VALUE', newState, propertyName };
}


The only difference is we pass it a 'propertyName' param aswell as the 'newState'. We now need to update our Redux reducer too, so it can handle the 'propertyName' param. Here's how it might look:

export default function data(prevState = {}, action, propertyName) {

    switch (action.type) {
    case 'SINGLE_REDUX_VALUE':
      return assign({}, prevState, {
        [action.propertyName]: action.newState
      });

    default:
      return prevState;
    }

}


If we called this twice with 2 different properties and values like this:

this.props.dispatch(actions.changeSingleReduxValue('Harry', 'firstName'));

this.props.dispatch(actions.changeSingleReduxValue('Jacks', 'lastName'));


Our Redux store would then look like this:

{
    data: {
        firstName: 'Harry',
        lastName: 'Jacks'
    }
}