Angular to React | Logo
 

Make Sure Your Redux Actions have all Expected Properties and Types

Looking for a job? With Hired, companies apply to you, not the other way around. It's free for candidates, plus you get a $1000 hiring bonus! Get started and find your dream job today!

Part 1 of 2

Part 2: Redux Action Creators and Reducers: Validating Redux Action Properties and Types

Recently, I came across this question on Stack Overflow.

Is there a best practice/recommended way to assert that a redux action is well-formed? I am a fairly noobish JavaScript programmer (coming at it from 20 years of C++/Java/C#) and thrown off by the lack of strong typing.

I’ve been working on a large React + Redux project with numerous Actions that must be consistent within their associated actions and reducers. I came up with an ES6 base class called ReduxAction. To use it, you just create a subclass that extends ReduxAction for every unique action in your application. In the constructor for your new class, you simply pass a map of property names that should be associated with that action and their expected types. Additionally, you pass the TYPE of action – the unique string key representing the action globally across your entire Redux application.

Here’s an example. First, import the ReduxAction class at the top of your file like this:

import ReduxAction from 'redux-action-validator'

Then, create your Action classes like this:

class MyAction extends ReduxAction {
  constructor(o) {
    super(MyAction.TYPE, {
      id:         ReduxAction.NUMBER,
      myList:     ReduxAction.ARRAY,
      mySample:   ReduxAction.STRING,
      myMap:      ReduxAction.OBJECT,
      myTest:     ReduxAction.BOOLEAN
    }, o)
  }
}

MyAction.TYPE = 'MY_ACTION'

If you pass any action through this new class and it either doesn’t have one of these required properties, or one of the properties is the wrong type it will throw a descriptive Error like this:

Error: Invalid Action Property for Type [MY_ACTION]: [id] expected to be type [number] but saw [array] instead.

You can get redux-action-validator directly from Github or move on to Part 2 of this article where you’ll learn how to use redux-action-validator in your Redux Action Creators and Reducers.

Hate paperwork but love getting paid? Invoice Like a Boss
Interested in Writing for Us?

Website developed by Michael Martin  (michael@angulartoreact.com
© 2015-16, All Rights Reserved