I am setting redux state in my componentDidMount function and then trying to access immediately and am not able to. I've stripped out some unnecessary complexity, but here's the basic setup:
// URL page?id=1
componentDidMount() {
this.props.setFilter({ location: this.props.location.search.id) });
console.log('in mount', this.props.filter);
}
// Action
export function setFilter(filterData) {
return {
type: SET_FILTERS,
payload: filterData
};
}
// Reducer
export default function(state = INITIAL_STATE, action = {}) {
switch(action.type) {
case SET_FILTERS: {
const newState = { ...state, filter: action.payload };
console.log('reducer state', newState);
return newState;
}
...
}
This will output
reducer state { location: 1 }
in mount {}
but if I change the componentDidMount to
componentDidMount() {
this.props.setFilter({ location: 1 });
setTimeout(() => { console.log(this.props.filter), 0; });
}
it works as expected and outputs
reducer state { location: 1 }
in mount { location: 1 }
Why would this be?
Thanks!