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.

Alejandro
  • 2,266
  • 6
  • 35
  • 63
  • i think what you're really asking here is how to display a modal or dialog box. take a look at this answer (by Dan abramov) https://stackoverflow.com/a/35641680/3148807 – Sagiv b.g Aug 14 '17 at 08:38

2 Answers2

1

There is no reason you can't use redux-thunk for this, in fact, on the official documentation for it, they even use a setTimeout as a way to emulate that async nature.

function showDialogAsync() {
  return dispatch => {
    setTimeout(() => {
       dispatch(showDialog());
    }, 5000);
  };
}

You can utilise this simple pattern where ever you want, be it for resetting the game or displaying dialogues.

Repo with Documentation

JEV
  • 2,494
  • 4
  • 33
  • 47
0

Redux-saga

Great for more complex async behaviour than redux-thunk

joejknowles
  • 350
  • 2
  • 12