Gergő Horváth
Gergő Horváth

Reputation: 3705

Redux doesn't initialize state

I've built up the next reducer structure:

//index.js

import userReducer from "./user";

const initState = {
    user: null
};

const rootReducer = (state = initState, action) => {
    const {
        user
    } = state;

    if (action === "SIGN_OUT") {
        return {
            user: userReducer(null, action)
        };
    }
    return {
        user: userReducer(user, action)
    };
};

export default rootReducer;

//user.js

const initState = {
    userId: null,
    clientId: null,
    type: null
}

const userReducer = (state = initState, action) => {
    switch (action.type) {
        case "SET_USER_ID" :
            const { userId } = action;
            return {
                ...state,
                userId
            };
        case "SET_USER_DATA" :
            const { userData } = action;
            return {
                ...state,
                ...userData
            };
        default : return state;
    };
};

export default userReducer;

Obviously, I have more reducers, it's for to simplify the demonstration.

My logic is that if the first parameter of userReducer is a falsy value, it will use initState. In the rootReducer the value of user is null, so inside userReducer, it should use initState as state.

Unfortunately my state looks like this:

{ user: null }

What am I doing wrong?

Upvotes: 0

Views: 199

Answers (2)

abadalyan
abadalyan

Reputation: 1235

Default argument values are applied only when undefined or no value is passed. Passing null and other falsy values apart from undefined will override the default value. More on that here.

Also as chrisheyn has pointed out in his answer, if (action === "SIGN_OUT") should be if (action.type === "SIGN_OUT")

Upvotes: 2

christian wuensche
christian wuensche

Reputation: 1043

in rootReducer you using the parameter action as a string ("SIGN_OUT"). Then you pass this var into userReducer and you're trying to read a string from action.type. Thats probably the problem.

I'm not sure but it seems that you trying to combine multiple reducer in rootReducer, right?

Check the buildin redux function combineReducers: https://redux.js.org/api/combinereducers

Upvotes: 1

Related Questions