RRR uzumaki
RRR uzumaki

Reputation: 1328

Executing a function after the action finished its working

Hey guys started out Redux today so was building a very basic Project of Incrementing/Decrementing the number on clicking the Increment/Decrement button. Here is a small code for it !Please have a look

Actions-creater file

export const increment=(num)=>{
    return {
        type:'increment',
        payload:num
    }
}

reducers file

const change=(change=0,action)=>{
    if(action.type==='increment'){
        return action.payload+1
    }
    return change
}
export default combineReducers({
    change
})

Increment.js

class Increment extends Component {
    render() {

        console.log(this.props.ans)
        return (
            <div>
            <button onClick={()=>{this.props.increment(this.props.ans)}}>Increment</button>
            </div>
        )
    }
}
const mapstatetoprops=(state)=>{
    return {ans:state.change}
}
export default connect(mapstatetoprops,{increment}) (Increment)

Now the issue I am facing is that in Increment.js on clicking the button Increment two functions get executed

First one

this.props.increment(this.props.ans)
//which calls the action creater and changes the state

Second one

this.props.in(this.props.ans)
//which is a callback to the parent component as i want to pass the value to app.js from both Increment/Decrement.js and then render it to screen

So my App.js looks like

const App=(props)=>{
console.log(props)
  return (
    <div>
     <Increment />
     <Decrement/>
   Count: {props.ans}
    </div>
  );
  }

const mapstatetoprops=(state)=>{
console.log(state)
return {ans:state.change}
}

export default connect(mapstatetoprops) (App);

Now if i console.log(val) in App.js and console.log(this.props.ans) in Increment.js file i find that if my original value is 0 so this.props.ans in Increment.js gives me 1 but in App.js this.val still gives me 0..so before the action updates the state i am receving value in App.js. How can i make that run and update App.js after action succesfully updates the state ?

Upvotes: 2

Views: 240

Answers (1)

thelonglqd
thelonglqd

Reputation: 1862

The running flow of your action is:

  • this.props.increment(this.props.ands) runs, at this point, this.props.ans is 0
  • this.props.in(this.props.ans) runs right after and print 0 in your App.js
  • The state changed and Increment Component re-rendered
  • console.log(this.props.ands) (in render function) runs.

To have the behavior as you want, you can call your in callback function inside the componentDidUpdate life cycle method.

componentDidUpdate(prevProps) {
  this.props.in(this.props.ans);
}

Upvotes: 2

Related Questions