Javascript: localStorage.getItem(key) not working

13.4k views Asked by At

I am trying to use local storage to store some texture objects but it doesn't seem to work.

for (var i = 0; i < 6; i++) {
    localStorage.setItem("name" + i, Transition.blurPano.getTexture(path + img_name[i] + ".jpg", dfrd[i], true, i));

    console.log(localStorage.getItem("name" + i) == Transition.blurPano.getTexture(path + img_name[i] + ".jpg", dfrd[i], true, i));

        Transition.blurPano.mesh.material.materials[i].map = localStorage.getItem("name" + i);
    }

Here I am trying to store a key value pair in the local storage with key = "name" + i and value is the texture object which is returned by the gettexture function, but this doesn't seem to work.

1

There are 1 answers

2
AkshayJ On BEST ANSWER

You cannot store objects in localstorage directly. A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var name = { 'first': 1, 'second': 2, 'third': 3 };

// Put the object into storage
localStorage.setItem('name', JSON.stringify(name));

// Retrieve the object from storage
var retrievedObject = JSON.parse(localStorage.getItem('name'));