Arian Shahalami
Arian Shahalami

Reputation: 1449

react redux-thunk wraps state inside another state

Im new to react, now Im creating a simple app using redux and redux-thunk which calls an API asynchronously. Here is my game gameAction:

export const fetchGamesStartAsync = () => {
return dispatch => {
    dispatch(fetchGamesStart());
    axiosGenCfg.post('/game/get',{
        "page" : 1,
        "size" : 10
    })
        .then(({ res }) => {
            dispatch(fetchGamesSuccess(res));
        })
        .catch(err => {
            dispatch(fetchGamesFailure(err.message));
        });
}
};


const fetchGamesStart = () => ({
    type: gameActionTypes.FETCH_GAMES_START,
});

const fetchGamesFailure = () => ({
    type: gameActionTypes.FETCH_GAMES_FAILURE,
});

const fetchGamesSuccess = (games) => ({
    type: gameActionTypes.FETCH_GAMES_SUCCESS,
    payload:{
        ...games
    }
});

and this is my gameReducer:

const INITIAL_STATE= {
    gamesList : null,
    isFetching: false,
    errorMessage : undefined
};

const gameReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case gameActionTypes.FETCH_GAMES_START:
            return{
                ...state,
                isFetching: true
            };
        case gameActionTypes.FETCH_GAMES_SUCCESS:
            return{
                ...state,
                isFetching: false,
                gamesList: action.payload
            };
        case gameActionTypes.FETCH_GAMES_FAILURE:
            return{
                ...state,
                isFetching: false,
                errorMessage: action.payload
            };
        default:
            return {
                state
            };
    }
};

and in rootReducer

export default combineReducers({
    admin : adminReducer,
    game: gameReducer,

})

I also added redux-logger to check state and this is what i get in console enter image description here

So why there are 2 levels of state in my game object? and also the same with admin object. before i add redux-thunk to project, I didn't have this problem. before adding redux-thunk currentAdmin was direct child of admin. But now there is a state object between.

Upvotes: 0

Views: 45

Answers (1)

dave
dave

Reputation: 64657

default:
        return {
            state
        };

should just be

default:
        return state

Right now any time you hit the default, state.whatever is becoming state.state.whatever

Upvotes: 1

Related Questions