Why are my props `undefined` when using redux and react.js?
Why is this.props.eventPassed logged as "undefined"?:
The action function (
eventPassed
) you are trying to access at this point does not exist atthis.props.actions.eventPassed
. It actually exists solely onthis.props.actions
.This is because you bound the action method to the value 'actions' in your mapDispatchToProps. This is turn provides gives access to the
eventPassed
action viathis.props.actions
.Since this.props.actions points to
eventPassed
, by trying to accessthis.props.actions.eventPassed
you are trying to access the property of 'eventPassed' on the actioneventPassed
. The result is that when you log for this property you receive "undefined"
Other necessary amendments:
mapDispatchToProps
needs to return a value
An arrow function with a block body does not automatically return a value and therefore one must be defined. So your function needs to look like:
mapDispatchToProps = (dispatch) => {
return { actions: bindActionCreators(eventPassed, dispatch) }
}
Initial state is an array containing an object:
const initialState = [{
eventPassed: false
}];
Since you're trying to reference it later as an object { eventPassed: true}
and not an array of objects [ { eventPassed: true } ]
it should be:
const initialState = {
eventPassed: false
};
The reducer needs to pass back the correct updated (but unmutated) state:
export default function eventPassed(state = initialState, action) {
switch (action.type) {
case actionTypes.EVENT_PASSED:
return {
...state,
eventPassed: action.payload
};
default:
return state;
}
}
What you were initially doing was returning a state that was no longer an object (or in the original case an array of object) but just the value of true
In your reducer
you initialize your state with array of object has eventPassed
property, meanwhile you return just the boolean and that's not correct because it replace the initial state, so the initState could be just an object holding the boolean, and you must return the state based on the payload
sent with the action dispathed to be as follow:
import * as actionTypes from '../constants/action-types.js';
const initialState = {
eventPassed: false
};
export default function eventPassed(state = initialState, action) {
switch (action.type) {
case actionTypes.EVENT_PASSED:
return {
...state,
eventPassed: action.payload
};
default:
return state;
}
}
Also, in your component
you may need to change:
this.props.eventPassed
to this.props.actions.eventPassed