简体   繁体   中英

JSON.parse() from localStorage issue

I am currently working on a little browser game and I am using the HTML localStorage to save some data.

The problem: I have an empty array that i will later .push() some data into. I am storing this array in the localStorage but when i try to read from the local storage it doesn't work.

The Chrome Developer Tools console is giving me this error: "Uncaught SyntaxError: Unexpected token u" when trying to parse the data from localStorage.

Here's the code i am using:

var allContracts = [];
localStorage["allContracts"] = JSON.stringify(allContracts);

allContracts = JSON.parse(localStorage["allContracts"]);

There is more code than this but none of it is interacting with these in any way.

Is there a quirk with localStorage or JSON that i am not aware of and is causing this? (i am not very familiar with JSON or localStorage) Should i be doing this a different way? Or am i just missing an obvious mistake?

Thanks in advance:)

The best way is to use the methods that the interface of localStorage serves to you. It have setItem() and getItem() methods, so why not use to safe yourself?

var allContracts = [];
// setter
localStorage.setItem("allContracts",  JSON.stringify(allContracts));
//getter
var allContracts = JSON.parse(localStorage.getItem("allContracts"));

With your piece of code, you are overriding the localStorage global object with your own values, so you lost the functionality.

You make this:

localStorage = [] // transform the default localstorage into an array

And you need this:

localStorage.setItem(key, value)

More info: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

I have only just started using localStorqage myself, but it looks like you should be using window.localStorage.setItem() and window.localStorage.getItem()

You can use Reusable Approach like this.

export const localData = {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    get(key) {
        const stored = localStorage.getItem(key);
        return stored == null ? undefined : JSON.parse(stored);
    },
    remove(key, value) {
        localStorage.removeItem(key);
    }
};

localData.set("user_name", "serialCoder")
console.log( "After set 👉", localData.get("user_name") )

localData.remove("user_name")
console.log( "After remove 👉", localData.get("user_name") )

You should use

localStorage.setItem('allContracts', JSON.stringify(allContracts));
localStorage.getItem('allContracts');

More details here: https://developer.mozilla.org/en-US/docs/Web/API/Storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM