Jatin Garg
Jatin Garg

Reputation: 346

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')

Upvotes: 0

Views: 55

Answers (2)

Mohammad Sadman
Mohammad Sadman

Reputation: 39

With hooks its much easier wrap your root with store

import {Provider} from 'react-redux';

const App = () => {    
    return (
    <Provider store={store}>
        <Yourcomponent/>
    </Provider>
  );
};

export default App;

Access your state in any component like this

import { useSelector } from "react-redux";
const state = useSelector(state => state)

Upvotes: 1

Kishan Bharda
Kishan Bharda

Reputation: 5700

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
});

Upvotes: 2

Related Questions