Search code examples
javascriptreactjsfluxredux

How to enforce data constraints in redux


I have a redux/react app that contains an array. Each element of this array has a number property, and the sum of these cannot be more than 3. Thus any of these options is okay:

arrayState: [
   {id: "a", number: 3}
]

arrayState: [
   {id: "a", number: 1},
   {id: "b", number: 2}
]

arrayState: [
   {id: "a", number: 1},
   {id: "b", number: 1}
   {id: "c", number: 1}
]

I then have a reducer that adds a new array item, and one that edits the number of an existing item (this uses the React Update Addon syntax which is hopefully self explanatory)

function items(items = INITIAL_STATE, action) {
    switch (action.type) {
        case actionTypes.ADD_ITEM
            return update(items, {$push: [INITIAL_STATE[0]]});
            break;
        case actionTypes.SET_ITEM_NUMBER:
            return update(items, {[action.index]: {number: {$set: action.number}}});
            break;
    }
    return items;
}

How, and at what point in my app (action creator, reducer, selector, or React components) should I implement this 'maximum 3' rule? In theory I could reject any action that would increase the count above 3, but I don't know the best practise way to do this with redux.


Solution

  • I think this would work best in the reducer. For each of these actions, if the new set of items is valid then return that new set, else return the current items and possibly set an error along with it.