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.
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM