Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected token U in JSON at position 0 – Not able to store data

I am trying to store my products in Vuex, but for some reason it displays this error:

"app.js:6693 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()"

This is the part of the code which is conflicting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default new Vuex.Store({
    state: {
        products: JSON.parse(localStorage.getItem('products')) ? JSON.parse(localStorage.getItem('products')) : [],
}

For some reason I was able to retrieve the data using this code, but after a while my website goes blank. I have a suspicion that it has to do with me setting this localStorage variable whenever I enter a page because it does that in the beforeMount lifecycle hook.

Does anyone have a clue how I can fix this issue? Thanks in advance!

>Solution :

You are trying to parse undefined as JSON string (position 0 of undefined holds u token). I guess you wanted to check if there are any products saved first, but accidentally wrapped condition in JSON.parse.

Look at the following snippet. This way it should work just fine.

products: localStorage.getItem('products') ? JSON.parse(localStorage.getItem('products')) : [],
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading