简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM