Mustehssun Iqbal
Mustehssun Iqbal

Reputation: 566

Somehow getting updated state in reducer

I am a beginner in react.js. I am making a board game as a beginner project. There is a component which rolls the dice. When the dice is rolled, an action is dispatched so that the state is changed to reflect values of that rolled dice. But in the reducer, both the values of state and action.data are same. How is that possible?

I have a dice rolling component which return this:

return (
            <div>
                <button
                onClick={this.rollDice.bind(this)}
                >
                    Roll dice!
                </button>

                <TurnDisplay dispatch={this.dispatch} />

                <BoardContainer dispatch={this.dispatch}  />
            </div>
        );

When you click the button, an action is dispatched, which is supposed update the state by adding dice values in it.

rollDice(){
        console.log("this.props ||||| rollDice()", this.props);
        if(this.props.isDiceRolled){
            alert("Move the marker...");
            return;
        }
        this.props.dispatch({
            type: "ROLL_DICE",
            data: {
                dice: Math.ceil(Math.random() * 5),
                isDiceRolled: true
            }
        });
    }

In reducer:

switch(action.type){

    .
    .
    .

    case "ROLL_DICE": {
        console.log("ROLL_DICE");
        console.log(state, action.data);
        const newTurn = Object.assign(state.currentTurn, action.data);
        return Object.assign(state, { currentTurn: newTurn });
    }
    default: {
        return state;
    }

}

Upvotes: 0

Views: 142

Answers (1)

maxgallo
maxgallo

Reputation: 478

With Redux, in the reducers, every time you have to return a new state. So instead of these two lines:

const newTurn = Object.assign(state.currentTurn, action.data);
return Object.assign(state, { currentTurn: newTurn });

You should write something like this

const newTurn = Object.assign({}, state.currentTurn, action.data);
return Object.assign(
    {},
    state,
    { currentTurn: newTurn}
)

The problem should be with Object.assign. Read more here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Upvotes: 4

Related Questions