D
D
Dmitry2017-05-26 13:17:33
React
Dmitry, 2017-05-26 13:17:33

What is the correct way to use reducer?

Help advice. I started learning redux and got a little stuck on compiling a reducer.
Example

const initialState = {state: 'start'};

export default function stateGame(state = initialState, action) {
    
    switch (action.type){
        case 'CHANGE_GAME_STATE':
            return {state: action.payload};
        default:
            return state;
    }
}

This reducer should change the state of the game. That is, I pass the state to payload (for example, end, start, pause) and then change the state of the component. Or it would be more correct to make such a reducer
const initialState = {state: 'start'};
export default function stateGame(state = initialState, action) {
    
    switch (action.type){
        case 'GAME_START':
            return {state: 'start'};
        case 'GAME_END':
            return {state: 'end'};
        case 'GAME_PAUSE':
            return {state: 'pause'};
        default:
            return state;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alvvi, 2017-05-26
@salarimus

Everything is in the docks on this subject, albeit in a not entirely obvious place
That is: at your discretion.
I personally prefer the first option, but the second one is more "understandable".

N
Nikita Gushchin, 2017-05-29
@iNikNik

Focus on the logic of your application.
If you need to register for GAME_START\GAME_... messages, then the second option is also possible. But the first one looks prettier. Unless, of course, you make several action creators for it like: startGame, endGame, pauseGame

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question