0

So I have a redux store in my react-project. The variables in the redux state like the user are subscribed to localStorage items to prevent resetting of values.

My store:

const pixStore = createStore(
combinedReducers, /* preloadedState, */
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

pixStore.subscribe(() => {
  localStorage.setItem('token', pixStore.getState().token);
  localStorage.setItem('user', pixStore.getState().user);
});

reducers:

import {combineReducers} from 'redux';
import {UserReducer, tokenReducer} from './authReducers';

// combine all reducers here
const combinedReducers = combineReducers({
    user: UserReducer,
    token: tokenReducer,
})

export default combinedReducers;

So when an action is dispatched, I want to set some values of the redux state to null. this is how am doing it now.

const tokenReducer = (state=localStorage.getItem('token'), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_TOKEN":
            /* Set token if not exists or update the existing token */
            return state = action.payload;
        case "CLEAR_TOKEN":
            return state = null;
    }
}

when I do this, the localStorage item's value is set to null but the state variable's value becomes "null" like it's a string. Because of this my functions don't detect the state variable to be null and it causes a lot of issues.

Why is this happening? Anyway I can fix it? please help me, thanks!! enter image description here

1
  • have you checked the type of pixStore.getState().token and ixStore.getState().user? If those a fetch result then maybe its already a string Commented Nov 24, 2020 at 12:06

1 Answer 1

2

use JSON.parse method here, LocalStorage.getItem will always give stringified value so null become 'null' to get the real data need to use JSON.parse.

state=JSON.parse(localStorage.getItem('token'))

so our reducer should be like this

const tokenReducer = (state=JSON.parse(localStorage.getItem('token')), action) => {
    switch(action.type){
        default:
            return state;
        case "REFRESH_TOKEN":
            /* Set token if not exists or update the existing token */
            return state = action.payload;
        case "CLEAR_TOKEN":
            return state = null;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot for the answer, it works and now I have a better understanding of JSON.parse I can accept answer only after 10 min though ;)
stackoverflow.com/questions/64999492/… this is the other question
can u pls help me with it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.