Reputation: 1774
I am getting the Redux state updated correctly. Here is what the Redux state of updateNeeded
is (In this case it is true).
I am console logging the value this.props.mandatory_fields.updateNeeded
but it is always the initial state that I set. It is not getting updated from the Redux State. Below is the code where I make the api call.
class CompleteProfile extends Component {
state = {
completeProfile: false,
}
componentDidMount = () => {
let { dispatch, session } = this.props
dispatch(getMandatoryFields(session.username))
console.log(
'this.props.mandatory_fields.updateNeeded -- ' +
this.props.mandatory_fields.updateNeeded
)
if (this.props.mandatory_fields.updateNeeded !== false) {
this.setState({
completeProfile: this.props.mandatory_fields.updateNeeded,
})
}
}
...
...
....
const mapStateToProps = state => ({
mandatory_fields: state.User.mandatory_fields,
session: state.User.session,
})
export default connect(mapStateToProps)(CompleteProfile)
The console log result is
this.props.mandatory_fields.updateNeeded -- false
It should be true
as shown in the Redux state image above. What am I missing ?
Upvotes: 2
Views: 3848
Reputation: 458
You must check this.props.mandatory_fields.updateNeeded
in componentDidUpdate
hook. After you change Redux state, the Component will be updated. So you must check props
in componentDidUpdate
instead of right after you call dispatch. You can see my code:
componentDidUpdate(prevProps, prevState, snapshot) {
console.log(
'this.props.mandatory_fields.updateNeeded -- ' +
this.props.mandatory_fields.updateNeeded
)
}
Your code will become:
class CompleteProfile extends Component {
state = {
completeProfile: false,
}
componentDidMount(){
let { dispatch, session } = this.props
dispatch(getMandatoryFields(session.username))
}
componentDidUpdate() {
console.log(
'this.props.mandatory_fields.updateNeeded -- ' +
this.props.mandatory_fields.updateNeeded
)
if (this.props.mandatory_fields.updateNeeded !== false) {
this.setState({
completeProfile: this.props.mandatory_fields.updateNeeded,
})
}
}
...
...
....
const mapStateToProps = state => ({
mandatory_fields: state.User.mandatory_fields,
session: state.User.session,
})
export default connect(mapStateToProps)(CompleteProfile)
Upvotes: 4
Reputation: 1517
With @Max's solution, your whole new code should be like this:
componentDidUpdate(prevProps) {
let { dispatch, session } = this.props
dispatch(getMandatoryFields(session.username))
console.log(
'this.props.mandatory_fields.updateNeeded -- ' +
this.props.mandatory_fields.updateNeeded
);
if (!prevProps.mandatory_fields.updateNeeded && this.props.mandatory_fields.updateNeeded) {
this.setState({
completeProfile: this.props.mandatory_fields.updateNeeded,
})
}
}
Upvotes: 1