Reputation: 12729
could you please tell me why not getting updated props value in react.
here is my code https://stackblitz.com/edit/react-redux-basic-counter-1e8gdh?file=shared/components/NavBar.js
In my example I have a button -
.on click it decrement the value. I dispatch the action value is decremented
but I am not getting updated value
handle=()=>{
this.props.decrement();
this.getCount();
}
getCount=()=>{
const {counter}= this.props;
console.log(counter);
}
see my console.log
expected output is -1
current output is 0
why? It is showing output when I click on -
button
Upvotes: 1
Views: 90
Reputation: 4471
The reason is at the point of printing the value in the console the props are not updated. When the props are updated the react component re-renders and display the counter value. To check that you can use a setTimeout
.
handle=()=>{
this.props.decrement();
setTimeout(this.getCount,10)
}
if you want to console log the value you can you the life cycle. you can use componentDidUpdate
componentDidUpdate(prevProps) {
if (this.props.counter !== prevProps.counter) {
console.log(this.props.counter);
}
}
or componentWillReceiveProps (for react version < 16)
componentWillReceiveProps(newProps) {
if( newProps.counter != this.props.counter ) {
console.log(newProps.counter);
}
}
or else getDerivedStateFromProps (react version 16 +)
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.counter !== prevState.counter ) {
console.log(nextProps.counter);
}
}
Upvotes: 3