1

I have been able to create a persistent local storage that allows the user to login and stores a randomly generated API token, which is necessary to communicate with the API.

The issue that I am having, is that my sign out button does not work anymore because the session store keeps the login information and token in the local storage and doesn't delete unless I manually do it.

Below is my code.

import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "../reducers";
import thunk from "redux-thunk";

function saveToLocalStorage(state) {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem("state", serializedState);
  } catch (e) {
    console.log(e);
  }
}

function loadFromLocalStorage() {
  try {
    const serializedState = localStorage.getItem("state");
    if (serializedState === null) return undefined;
    return JSON.parse(serializedState);
  } catch (e) {
    console.log(e);
    return undefined;
  }
}

const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ 
    || compose;

const persistedState = loadFromLocalStorage();

const store = createStore(
  rootReducer,
  persistedState,
  storeEnhancers(applyMiddleware(thunk))
);

store.subscribe(() => saveToLocalStorage(store.getState()));

export default store;
  • window.localStorage.removeItem(key) should be triggered programmatically – SamwellTarly Feb 03 '20 at 16:46
  • 1
    Usually session keys expire after some period of time and need to be refreshed, which handles scenarios where the user simply closes a browser window (thus your code can't run). You aren't trying to [roll your own security](https://security.stackexchange.com/questions/18197/why-shouldnt-we-roll-our-own), are you? – JDB Feb 03 '20 at 16:50
  • A variation of this question has been asked and answered multiple times already. Even if you're not using JWT, read [this](https://stackoverflow.com/questions/37959945/how-to-destroy-jwt-tokens-on-logout). – Tomasz Kasperczyk Feb 03 '20 at 18:47
  • Please see code above. Like I said, I was able to create a persisting storage and have tried several variations of this to try and refresh the set api token, but I am not sure why it doesn't clear in the local session storage. – TheAlkhemist Feb 04 '20 at 20:11

0 Answers0