Redux-handling async action dispatch

Redux-handling async action dispatch
0

#1

Maybe I am overthinking this, but so far most of the stuff I’ve read on redux-thunk handles async calling from API, etc.

Ideally I would like to have the same behavior but for UI’s transition.

For instance, let’s say I have a game that for simplicity, it requires two players, and each player has a turn to guess a name.

If the player’s guess is matched, then I want to display the dialog for 5 seconds, and then reset the game.

Otherwise, display a dialog that indicates it’s the next player’s turn for 5 seconds.

I have the following code:

class Game extends Component {
  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(nextProps) {
    const { isMatchedNumbers } = nextProps
    if (isMatchedNumbers) {
      this.props.showDialog('You win!')
      this.props.resetGame()
    } else {
      this.props.showDialog('next turn')
      this.props.nextTurnPlayer()
    }
  }

  render() {
    ...
  }
}


const mapStateToProps = (state, props) => ({
  isMatchedNumbers: state.isMatchedNumbers
})

const mapDispatchToProps = dispatch => ({
  nextTurnPlayer: () => {
    dispatch({ type: NEXT_TURN_PLAYER })
  },
  showDialog: message => {
    dispatch({ type: MESSAGE, message })
  },
  resetGame: () => {
    dispatch({ type: RESET_GAME })
  },
  
})

export default connect(mapStateToProps, mapDispatchToProps)(Game)

How would I be able to achieve this?
I thought about adding setTimeOut inside mapDispatchToProps, but I feel that it is not the right way.


#2

There is no problem in using setTimeOut if you need to delay the execution of some code, just make sure to use clearinterval() function.

To check the syntax : https://www.w3schools.com/jsref/met_win_clearinterval.asp