Using React PropTypes and defaultProps pattern with Redux-ORM models

January 16, 2016 ยท View on GitHub

import { PropTypes } from 'react'; import { Model } from 'redux-orm'; import getEnv from 'get-env';

const env = getEnv();

class ValidatingModel extends Model { static _validateProps(props) { if (typeof this.propTypes === 'object') { forOwn(this.propTypes, (validator, key) => { const result = validator(props, key, this.modelName); if (result instanceof Error) { throw result; } }); } }

static create(props) {
    const defaults = this.hasOwnProperty('defaultProps')
        ? this.defaultProps
        : {};
    const propsWithDefaults = Object.assign({}, defaults, props);

    if (env !== 'prod') {
        this._validateProps(propsWithDefaults);
    }

    return super.create(propsWithDefaults);
}

};

// Use like this:

export class Person extends ValidatingModel { } Person.modelName = 'Person'; Person.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number.isRequired, isFetching: PropTypes.bool.isRequired, }; Person.defaultProps = { isFetching: false, };