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:
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')) : [],