'Uncaught SyntaxError: Unexpected token u in JSON at position 0 in Vuex

I am sending data from vuex to localStorage, and then trying to set data from localStorage to state 'cart'.

import axios from 'axios'
import { createStore } from 'vuex'

export default createStore({
  state: {
    cart: [],
    products: []
  },
  getters: {
    cart: state => {
      return state.cart
    },
    products: state => {
      return state.products
    }
  },
  mutations: {
    addToCart(state, product) {
      localStorage.carts = JSON.stringify(product)
      return state.cart.push(product)
    },
    removeProduct(state, item) {
      localStorage.removeItem('carts', item)
      return state.cart.pop()
    },
    SET_PRODUCTS(state, products) {
      state.products = products
      state.filteredProducts = products
    }
  },
  actions: {
    addToCart(context, product) {
      context.commit('addToCart', product)
    },
    removeProduct(context, item) {
      context.commit('removeProduct', item)
    },
    fetchProducts({ commit }) {
      return axios.get('http://localhost:3000/products?_limit=4&_page=1').then(res => {
        commit('SET_PRODUCTS', res.data)
      })
    }
  }
})

I have tried adding this line to the state cart

cart: [JSON.parse(localStorage.carts)]

but this only works if localStorage is not empty(if it already has something), if not it will throw error

Uncaught SyntaxError: Unexpected token u in JSON at position 0 

Cart component:

<template>
    <div class="cart-container">
        <div class="header">
            <p>NARUZDBA</p>
            <div>
                <img src="../assets/icons/close.png" class="icon" @click="this.$store.commit('customChange')" />
            </div>
        </div>

        <div class="products" v-for="item in cart" :key="item.id">
            <div class="product">
                <div>
                    <p class="amount">1x</p>
                    <p>{{ item.name }}</p>
                    <icon name="remove" class="remove" @click="removeProduct(item)"></icon>
                </div>
                <p class="price">{{ item.price }}kn</p>
            </div>
        </div>

        <router-link to="/cart">
            <button class="btn">Kosarica</button>
        </router-link>
        <div class="outside" @click="away"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import Icon from './icons/Icon.vue'

export default {
    components: { Icon },
    methods: {
        away() {
            this.$store.commit('customChange')
        },
        removeProduct(item) {
            this.$store.commit('removeProduct', item)
        }
    },
    computed: {
        ...mapState(['cart'])
    }
}
</script>

This is now showing '1x', remove button, and 'kn'



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source