Boris Grunwald
Boris Grunwald

Reputation: 2712

can't map state to props when using combinereducers

I'm trying to map my state to a given component with redux. I have two reducers and are therefore using combineReducers before passing my rootReducer to my store.

const rootReducer = combineReducers({
    ctr:counter,
    res:result
});

const store = createStore(
    rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));
registerServiceWorker();

But when I try mapping my state to a given component's props, the state is undefined

const mapStateToProps = state => {
    return {
        ctr: state.ctr.counter,
        storedResults: state.res.results //storedResults is undefined when I try to access it.
    }
};

My two reducers look as follows:

counter.js

import * as actionTypes from "../actions";


const initialState = {
    counter:0
};

const reducer = (state = initialState, action) => {

    switch (action.type) {
        case actionTypes.INCREMENT:
            return {
                ...state,
                counter: state.counter + 1
            };
        case actionTypes.DECREMENT:
            return {
                ...state,
                counter: state.counter - 1
            };
        case actionTypes.ADD:
            return {
                ...state,
                counter: state.counter + action.val
            };
        case actionTypes.SUBTRACT5:
            return {
                ...state,
                counter: state.counter - 5
            };
    }

    return state;
};


export default reducer;  

result.js

import * as actionTypes from "../actions";


const initialState = {
    result:[]
};

const reducer = (state = initialState, action) => {

    switch (action.type) {
        case actionTypes.STORE_RESULT:
            return {
                ...state,
                results:state.results.concat({id: new Date(), value:state.counter})
            };
        case actionTypes.DELETE_RESULT:
            // const id = 2;
            // const newArray = [...state.results];
            // newArray.splice(id,1);

            const updatedArray = state.results.filter(result => result.id !== action.resultId);

            return {
                ...state,
                results:updatedArray
            }

    }

    return state;
};


export default reducer;

Any idea what the problem might be?

Upvotes: 0

Views: 529

Answers (1)

Vinayak Bagaria
Vinayak Bagaria

Reputation: 162

Your initialState in result reducer is result. Just correct it to results.

Upvotes: 1

Related Questions