user2394156
user2394156

Reputation: 1840

The proper way to implement different actions within the same event in redux

I'm trying to learn Redux with React so I'm developing a simple Poker game (Texas Hold'em) and I have a board where there is flop consisting of 3 cards, turn (1 card) and river (1 card)

enter image description here

Under the board I have a "Next phase" button, that when clicked, should fill the flop first, then within the next click add turn, and after another click add river

import React, {PropTypes} from 'react';

const PhaseButton = ({onClick}) => {

    return (
        <div id="phaseButtonContainer">
            <button onClick={onClick}>Next phase</button>
        </div>
    );

};

PhaseButton.propTypes = {
    onClick: PropTypes.func.isRequired
};

export default PhaseButton;

I also have action creators for each of these:

const addFlop = (cards) => {
    return {
        type: 'ADD_FLOP',
        cards: cards
    };
};

const addTurn = (card) => {
    return {
        type: 'ADD_TURN',
        card: card
    };
};

const addRiver = (card) => {
    return {
        type: 'ADD_RIVER',
        card: card
    };
};

Cards are provided from another service that picks them randomly.

The question is: Where should the logic for choosing card / cards and deciding which action to use be placed? It's quite complicated because different actions happen within the same button and I also have to read the state in order to know which phase to execute

Upvotes: 1

Views: 102

Answers (1)

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

Take a look at redux-thunk middleware. It allows you to dispatch as many actions as you need in one action creator. So the idea is that you have one action creator like

nextPhase = (cards) => {
  return dispatch => {
    // some logic
    dispatch(addFlop(cards));
    // more logic
    dispatch(addTurn(cards));
    // more logic
    dispatch(addRiver(cards));
  };
}

And you can dispatch different actions based on your logic. They could be async as well.

Upvotes: 3

Related Questions