Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the properties inside defaultState be null or ''

Tags:

reactjs

redux

Most of the tutorials online show that the properties inside initialState should be '' (if it is a string), like:

let defaultState = Immutable.fromJS({
    viewData: {
        id: '',
        name: '',
        alist: []
    }
});

But if you than have a habit of explicitly stating what properties a certain component uses, like:

function mapStateToProps(state) {
    return viewData: state.someReducer.get('data');
}

someContainer.propTypes = {
    data: ImmutablePropTypes.mapContains({
        id: React.PropTypes.string.isRequired,
        name: React.PropTypes.string.isRequired,
        aList: ImmutablePropTypes.list.isRequired
    }),
};

Than the only way i will get "Failed propType" is if any of the properties got removed from the reducer and the isRequired somehow feels redundant since it will always give an empty string which is than passed on to someContainer child components.

However, if i do:

let defaultState = Immutable.fromJS({
    data: {
        id: null,
        name: null,
        aList: null
    }
});

Than i will get a failed proptype if the reducer didn't populate the state, isnt this wanted? However since i rarely see others set the props to null i feels there is a good reason not to.

Also, going with the null method nesting Maps in state gets confusing since it than even viewData should be null, but then you lose the information with not showing what data it really will get:

let defaultState = Immutable.fromJS({
    viewData: { // Shouldnt this be null than as well?
        id: null,
        name: null,
        hierarchies: { // and this
            one: null,
            two: null
        }
    }
});
like image 633
user3711421 Avatar asked Feb 14 '17 13:02

user3711421


1 Answers

null is a perfectly acceptable form of default state - its an assignment value indicating that this particular property is without value.

There is a bigger question at play, which is totally dependent on your particular application (only you can answer if null makes sense), but to answer your particular question about it "being ok" - yes, it's ok.

I don't like using empty strings as default state, I find it misleading to the application. For example, my consuming components "understand" that a null value means a value has yet to be provided, whereas an empty string implies one has indeed been set, but it is simply empty (lets say, a user without a middlename - the value is ""). This allows the application deal with the current state of the app more appropriately.

Btw - its a very excellent question that isn't often explicitly explored in tutorials (as you mention).

like image 80
Chris Avatar answered Nov 16 '22 00:11

Chris