Redux reducer gets string instead of object

3545 views javascript
2

I am trying to update my state using redux, but for some reason the reducer only gets a string instead of an object.

// action    
const switchTab = (activeTab) => { return { type: SWITCH_TAB, activeTab } }

//reducer
const appUIManagement = (state = initialState, action) => {
    switch(action.type) {
        case SWITCH_TAB: 
            return Object.assign({}, state, action.activeTab);
        default:
            return state;
    }
}

Assuming my initial state is

{activeTab: 'lines'}

Now when I dispatch an action:

{ type:SWITCH_TAB, { activeTab: 'favorites' } },

the state parameter of my reducer is only 'lines' instead of the whole object and because of this my response looks something like

{activeTab: { 0:'f',1:'a',2:'v'....}

What am I doing wrong or what is it that I'm not getting about redux? Thank you

answered question

You are using action.activeTab in Object.assign, shouldn't it be { activeTab: action.activeTab} ?

Well that was what I did initially, and that would make sense. But that just creates something like {actionTab: {actionTab: 'test'}}

1 Answer

5

You are passing the string action.activeTab into Object.assign

const state = {};
const action = { type: 'SWITCH_TAB', activeTab: 'lines' };
const newState = Object.assign({}, state, action.activeTab);
console.log(newState);

However, Object.assign expects objects as its arguments so you should pass the whole action or better yet the portion of the action that you need:

const state = {};
const action = { type: 'SWITCH_TAB', activeTab: 'lines' };
const newState = Object.assign({}, state, { activeTab: action.activeTab })
console.log(newState);

posted this

Have an answer?

JD

Please login first before posting an answer.