Search code examples
javascriptreact-nativereduxreducers

Unable to access Reducer & state values


I am unable to access my state values saved in store on any screen. values reach to actions but when I access it from store it returns always undefined. Every thing is in separate files

Reducer 1

import * as Actions from '../actionTypes'
import initialStore from './initialStore'

const homeModuleReducer = (state = initialStore, action) => {
    switch (action.type) {
        case Actions.SET_PROFILE_ONE:
            console.log('call here')
            return {
                ...state,
                currentUser: action.profile
            }
        default:
            return state;
    }
}

export default homeModuleReducer

Reducer 2

import * as Actions from '../actionTypes'
import initialStore from './initialStore'

const loginModuleReducer = (state = initialStore, action) => {
    switch (action.type) {
        case Actions.SET_PROFILE:
            return {
                ...state,
                currentUser: action.profile
            }
        case Actions.SET_INITIAL_LOADING_STATUS:
            return {
                ...state,
                isInitialLoadingDone: action.loadingStatus
            }
        default:
            return state;
    }
}

export default loginModuleReducer

Combine Reducer

import { combineReducers } from 'redux'
import homeModuleReducer from './homeModuleReducer'
import loginModuleReducer from './loginModuleReducer'

export default combineReducers({
    homeModuleReducer,
    loginModuleReducer,
})

Store

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

let store = createStore(rootReducer, applyMiddleware(thunkMiddleware));

export default store;

usage:

const mapStateToProps = (state) => ({
    stateLoaded: state.rootReducer.isInitialLoadingDone,
    profile: state.rootReducer.currentUser
});

Error:

undefined is not an object (evaluating 'state.rootReducer.isInitialLoadingDone')


Solution

  • You already combined your reducers so you can access reducer by it's key like this :

    const mapStateToProps = (state) => ({
        stateLoaded: state.homeModuleReducer.isInitialLoadingDone, // here homeModuleReducer is just an example. Change with reducer key in which isInitialLoadingDone is belong
        profile: state.loginModuleReducer.currentUser
    });