pageNotfoUnd
pageNotfoUnd

Reputation: 666

Unable to store and retrieve the state from redux store

import * as actions from '../actions/login.Action';

let initialState = {
    user: {
        loggedIn: false,
        userRole: "",
        userEmail: "",
    }
};

export default function (state = initialState, action) {
    switch (action.type) {
        case actions.LOGIN_SUCCESS:
            return {
                ...state,
                user: {
                    ...state.user,
                    loggedIn: true,
                    userRole: action.userRole,
                }
            };

        case actions.LOGOUT:
            return initialState;

        default:
            return state;
    }
}

this is my reducer triggered after the action login success and below is my store code

import { createStore, applyMiddleware, compose } from 'redux';
//import createSagaMiddleware from 'redux-saga';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
import rootReducer from './reducers';

const enhancers = [];
const middleware = [
    thunk,
    routerMiddleware(history)
];

export const history = createHistory();

const composedEnhancers = compose(
    applyMiddleware(...middleware),
    ...enhancers
);

export const store = createStore(
    rootReducer,
    persistedState,
    composedEnhancers
);


const persistedState = localStorage.getItem('state') ? JSON.parse(localStorage.getItem('state')) : {};


 store.subscribe(() => {
     localStorage.setItem('reduxState', JSON.stringify(store.getState()));
 });

in this case I am able to get the value from reducer but the issue is state value gets empty on page refresh whats wrong in this code i'm unable to identify clueless why the store doesn't save the state

Upvotes: 0

Views: 79

Answers (1)

MBehtemam
MBehtemam

Reputation: 7919

I think you first call persistedState then define it Look below :

export const store = createStore(
rootReducer,
persistedState,
composedEnhancers
);


const persistedState = localStorage.getItem('state') ? 
JSON.parse(localStorage.getItem('state')) : {};

How about to change the position of persistedState so after that you have :

const persistedState = localStorage.getItem('state') ? 
JSON.parse(localStorage.getItem('state')) : {};
export const store = createStore(
  rootReducer,
  persistedState,
  composedEnhancers
 );

Upvotes: 1

Related Questions