Skip to content Skip to sidebar Skip to footer

Dispatch(action) Changes The Store State But Component Is Not Updated

I have pretty simple code, the idea is to fetch some data via ajax and make them available for the whole life of app. I need it this way because I use the Index component in many p

Solution 1:

Basically in your mapStateToProps, you have options: state.options; but right now there is no thing named as options in the state. From the docs http://redux.js.org/docs/api/createStore.html, when you use createStore passing in setOptReducer as argument, it creates a store with just one reducer and as a result state on it's own is the value of the store.

Could you try changing your mapStateToProps to this?

functionmapStateToProps(state) {
    console.log("mapStateToProps ",state);
    return {options: state};
};

If this works, then you could rename some things, since right now it might be confusing. For example removing var options = [] and change the reducer function to options and have

const store = createStore(options, []);

It is recommended to use combineReducers to create a single root reducer out of many - and if you pass that to createStore, then the state is an object, and you can then do state.setOptReducer

Hope it's not too confusing

Solution 2:

Finally with huge help of luanped I got to the root of the problem, and I believe it worth putting as a separate answer.

mapStateToProps really cannot map state.options to options as the state doesn't contain options attribute, because in the setOptReduceractionData is being saved by concatenating it to the state array, not by putting as a separate named attribute of object state:

   case 'ADD_ITEM':
        return [
            ...state,
            action.data
        ]

So mapStateToProps doesn't really changes options (change is undefined to undefined) and that's why the component doesn't re-render. So the decision is to expose the whole state as options, which is changing this.props of the component, so it works. To make it work the more correct way, without exposing the whole state to the component, but just the options part, reducer's code should be:

return {
        ...state,
        options: action.data
    }

This way state becomes to have options attribute, mapStateToProps sees it and the component re-renders.

Post a Comment for "Dispatch(action) Changes The Store State But Component Is Not Updated"