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.

1
  • 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) stackoverflow.com/a/35641680/3148807 Commented Aug 14, 2017 at 8:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Redux-saga

Great for more complex async behaviour than redux-thunk

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.