user3554382 user3554382 - 1 month ago 25
Javascript Question

React Redux MapStateToProps

Why do I get

undefined
returned when I access the state? I use the Redux DevTools and see the state correctly updated via an action but I just cannot access the state values for some reason. I get this sort of object returned when I access
state.dog
which seems wrong:

ct {size: 1, _root: pt, __ownerID: undefined, __hash: undefined, __altered: false}


Here is my container code:

import { connect } from 'react-redux';
import Message from '../../components/message';

const mapStateToProps = (state) => {
console.log(state.dog.hasBarked);
return {
message: state.dog.hasBarked ? 'Barked' : 'It is quiet',
};
};

export default connect(mapStateToProps)(Message);


Here is the dog reducer:

import * as Immutable from 'immutable';
import { MAKE_BARK } from '../actions/dog';

const initialState = Immutable.Map({
hasBarked: false,
});

const dogReducer = (state: Object = initialState, action: Object) => {
switch (action.type) {
case MAKE_BARK:
return state.set('hasBarked', action.payload);
default:
return state;
}
};

export default dogReducer;

Answer

Seems like you are using immutable. state.dog is not a simple js array but a immutable map or list. You can access it natively with state.dog.toObject().hasBarked.

Comments