I am encountering an issue while trying to add items to a cart using vuex. The console is showing an error and the products on the page are not displaying correctly. Can someone please guide me on how to resolve this problem? The error in the console is:
client.js?06a0:103 SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Store.initializeStore (index.js?9101:14)
at wrappedMutationHandler (vuex.esm.js?2f62:844)
at commitIterator (vuex.esm.js?2f62:466)
at Array.forEach (<anonymous>)
at eval (vuex.esm.js?2f62:465)
at Store._withCommit (vuex.esm.js?2f62:624)
at Store.commit (vuex.esm.js?2f62:464)
at Store.boundCommit [as commit] (vuex.esm.js?2f62:409)
at VueComponent.mounted (default.vue?ec86:82)
Below is the store.js code where I am utilizing localStorage:
export const state = () => ({
cart:{
items:[],
},
isAuthenticated: false,
token: '',
isLoading: false,
})
export const mutations = {
initializeStore(state) {
if (localStorage.getItem('cart')) {
state.cart = JSON.parse(localStorage.getItem('cart'))
} else {
localStorage.setItem('cart', JSON.stringify(state.cart))
}
},
addToCart(state, item) {
const exists = state.cart.items.filter(i => i.product.id === item.product.id)
if (exists.length) {
exists[0].quantity = parseInt(exists[0].quantity) + parseInt(item.quantity)
} else {
state.cart.items.push(item)
}
localStorage.setItem('cart', JSON.stringify(state.cart))
},
}
export const actions = {
}
This is default.vue file where I am attempting to access localStorage from vuex:
export default {
data(){
return{
title:'QL Gadgets',
cart:{
items:[]
},
}
},
mounted(){
this.$store.commit('initializeStore')
},
computed:{
cartTotalLenght(){
let totalLenght = 0
for(let i=0; i < this.cart.items.length; i++){
totalLenght += this.cart.items[i].quantity
}
return totalLenght
}
},
methods:{
handleClick(){
if(this.$refs.menu.classList.contains('hidden')){
this.$refs.menu.classList.remove('hidden')
}
else{
this.$refs.menu.classList.add('hidden')
}
}
},
}