2
votes

I am trying to change state of a const in redux. i am trying my dispatch directly in the component i want to change the state in. The State is changed after dispatch,However i get back an Object. And when i Console.log , i get [Object][Object] , which before calling dispatch i used to get the Value of the state.

This is my Store.

import { createStore,applyMiddleware , compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

//const  initialState = {};

const middleware = [thunk];
const store = createStore(
    rootReducer,
    compose(
        applyMiddleware(...middleware),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )

);


export default store;

This is my Main Reducer.

import { combineReducers } from 'redux';
import sidebarReducer from './sidebarReducer';


export default combineReducers({
    name : sidebarReducer

});

This is my CustomReducer , which i call sidebarReducer.

import { TOGGLE_SIDEBAR } from '../actions/types';


let sidebarname = "wrapper slide-menu";


export default function(state=sidebarname,action){
    switch(action.type){
            case TOGGLE_SIDEBAR:
            console.log('reducer called');
            console.log(state);
                return{

                        ...state,
                        sidebarname :  action.payload

                };



    }
    return state;


}

This is my Dispatch and MapStatetoProps Function.

const mapStatetoProps = state  => ({
  name : state.name

});
const mapDispatchtoProps = dispatch => ({

  setName : (name) => {

        dispatch({

            type: "TOGGLE_SIDEBAR",
            payload: name 

        })

  }

})
export default connect(mapStatetoProps,mapDispatchtoProps)(App);

I successfully retrieved the State from the store , however when i dispatch i get back an Object.

sidebarReducer.js:13 reducer called
sidebarReducer.js:14 wrapper slide-menu
App.js:38 sidebarname is [object Object]
App.js:40 wrapper slide-menu
2
can you show us how you console logged it?Aseem Upadhyay
i console logged it in render() function of react component , after calling the dispatch function. and i get back [Object] [Object] . the console.log was console.log(this.props.name)codemt

2 Answers

5
votes

In handling your action, you are returning an object (check the curly braces):

return {
  ...state,
  sidebarname: action.payload
};

Since your entire state is only the string sidebarname, you should return only the payload:

return action.payload

Alternatively, you can have your state be an object, and then your action return should work just fine:

let initialState = { sidebarmenu: "wrapper slide-menu" };
...
export default function(state=initialState,action){
  ...
}
1
votes

your sidebarReducer just manages a string. just return action.payload on TOGGLE_SIDEBAR, not an object with a sidebarname property.