Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After a clear, localStorage remembers previous values

So, this is a bit strange. I'm using Backbone and Backbone.localStorage to save remote data to local storage for caching. Pretty standard stuff.

When I run a localStorage.clear() on the entire store, all values are cleared out permanently except for the key that has a string array of values. It gets cleared out on first inspection, but then when storage saves again with Backbone.LocalStorage.sync('create', model); the previous values are back in there.

Of course, if I manually delete the key within Chrome Developer Tools, then it stays gone and isn't repopulated. It's as if the localStorage.clear() call still caches keys with a string array. I've confirmed it is initially cleared out on app start.

I'll post some code and screenshots here on edit, but really it's pretty standard except for the fact those values remain after the key is repopulated. Any ideas here?

EDIT: Lots of fun code to look at:

Collection:

app.DiagnosisCollection = Backbone.Collection.extend({
    model: DiagnosisModel,
    localStorage: new Backbone.LocalStorage('diagnosis'),

    save: function(model) {
        Backbone.LocalStorage.sync('create', model);
    }
});

Model:

app.DiagnosisModel = Backbone.Model.extend({

    urlRoot: app.ApiRoot,
    url: app.DiagnosisApi,

    initialize: function(options) {
        if(!options.query) {
            throw 'query must be passed to diagnosisModel';
        }

        this.local = false;
        this._query = options.query;
    },

    sync: function(method, model, options) {
        var diagnosisKey = localStorage.getItem('diagnosis');
        var index, diagnosisStore;

        if(diagnosisKey) {
            diagnosisKey = diagnosisKey.split(',');
        }

        index = _.indexOf(diagnosisKey, this._query);

        if(index !== -1) {
            diagnosisStore = localStorage.getItem('diagnosis' + '-' + diagnosisKey[index]);
        }

        if(diagnosisStore) {
            this.local = true;
            options.success(JSON.parse(diagnosisStore));
        }
        else {
            this.local = false;
            var fetchUrl = this.urlRoot + this.url + this._query;
            $.getJSON(fetchUrl, function(data, textStatus) {
                if(textStatus !== 'success') {
                    options.error();
                }
                options.success(data);
            });
        }
    }
});

return app.DiagnosisModel;

Controller function that does the work:

        var self = this;

        // Create a new collection if we don't already have one
        // The save function puts it in local storage
        if(!this.diagnosisCollection) {

            this.diagnosisCollection = new DiagnosisCollection();

            this.diagnosisCollection.on('add', function(diagModel) {
                this.save(diagModel);
            });
        }

        var diagModel = new DiagnosisModel({
            query: diagId
        });

        diagModel.fetch({
            success: function() {
                var diagView = new DiagnosisView({
                    model: diagModel
                });

                if(!diagModel.local) {
                    self.diagnosisCollection.add(diagModel);
                }

                self._switchPage(diagView);
            },
            error: function() {
                console.error("Diag Model Fetch Failed");
                Backbone.history.navigate('503', { trigger: true });
            }
        });

By the way, localStorage.clear() call is in app start. It does an API call to see if the version on the server has changed. If the version has changed, then we nuke localStorage.

like image 699
Brandon Avatar asked Dec 20 '12 15:12

Brandon


People also ask

What happens when you clear local storage?

When you clear your localStorage and fill it right after, it kind of restore the previous content and adds you new item to it. When you clear your localStorage and doing a hardrefresh, it is empty and you can start filling it again.

Does localStorage persist after refresh?

localStorage demo Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

Does clearing localStorage clear cache?

Local Storage data will not get cleared even if you close the browser. Because it's stored on your browser cache in your machine. Local Storage data will only be cleared when you clear the browser cache using Control + Shift + Delete or Command + Shift + Delete (Mac)

How do I keep localStorage values after refreshing?

You can even select your stored value in the Local Storage panel, hit the Delete key, and refresh the page (or just clear your site data), where you'll see the banner reappear because you cleared the data. But then when you Hide it again, it'll persist that state. Follow along with the commit!


1 Answers

Instead of localStorage.clear(), use :

localStorage.removeItem('userInfo');

I have faced the same issue in my backbone application and i used this way to clear out the values.

P.s : Yes you need to specify all of your localstorage variables one by one..:(.. But this works well.

like image 72
Roy M J Avatar answered Oct 04 '22 13:10

Roy M J