Issues with resetting state stored in local storage, using redux-storage

1.1k Views Asked by At

I'm using react-storage in an app to persist my state in my local storage. In an attempt to clear the state, I do this:

import createEngine from 'redux-storage-engine-localstorage'
const engine = createEngine('my-save-key');

...

engine.save({})
.then( () => {
  dispatch({type: 'SOME_ACTION'})
})
...

engine.save({}) should theoretically save the state in my local storage to an empty object. After this is done, I expect the next dispatched action's previous state to be that empty object. However, somehow the action dispatched in the .then still has reference to the old state, and it's as if the state was never reset.

Also, I've been experimenting with localStorage.clear() to reset the state, but I encounter the same problem. Any ideas on what might be wrong, and how I might fix this?

1

There are 1 best solutions below

0
On

Well, it's doesn't look like Redux uses the state stored in localstorage unless it's told to do so with engine.load(). And that's a good thing. If using localstorage meant that Redux shouldn't keep its own state in memory, but always read from localstorage, that would be horrible for performance. engine.save() doesn't seem to do anything with the actual redux state, it just sets the localstorage value to something that you may load later, e.g. the next time you start the application.

engine.load() would typically be something you use to get the initial state of your application, and then use engine.save() any time you want to take a snapshot of the current state that can be reproduced at a later point. The source code for save() and load() should be pretty self-explanatory:

export default (key) => ({
    load() {
        let jsonState;

        try {
            jsonState = localStorage.getItem(key);
        } catch (err) {
            return Promise.reject(err.message);
        }

        return Promise.resolve(JSON.parse(jsonState) || {});
    },

    save(state) {
        const jsonState = JSON.stringify(state);

        try {
            localStorage.setItem(key, jsonState);
        } catch (err) {
            return Promise.reject(err.message);
        }

        return Promise.resolve();
    }
});