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

How to add item to local storage Vue 3 with Composition API

I’m trying to add cart item to localStorage in Vue 3. I’m using Composition API and and I’m just learning Vue, so please be understanding 😀

Okey, so it’s my code of single product view where I call to addProductToCart function

export default {
    props: {
        id: {
            required: true,
            type: String
        }
    },

    setup(props) {
        const { product, getProduct } = useProducts()

        onMounted(getProduct(props.id))

        let cartItems = ref([])

        function addProductToCart(product) {
            cartItems.value.push({...product})
            window.localStorage.setItem('CART', JSON.stringify(cartItems.value))
            console.log(JSON.parse(localStorage.getItem('CART')));
        }

        return {
            addProductToCart,
            product
        }
    }
}

Problem is when I reload page. State of cart items it’s stored but when I add another product after refreshing page the localStorage it’s reset.

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

Problem it’s here:

let cartItems = ref([])

Im trying to check if the localStorage is not null and when is not null I want add another products to exsisting state of cart product items so trying like this:

let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
    cartItems = window.localStorage.getItem('CART')
}

But when I click ADD TO CART button I receive error:

Uncaught TypeError: Cannot read properties of undefined (reading 'push')

I searched the internet for a lot of information about the state of carts but I found nothing sensible where they represent storage of cart states using the Composition API.

Maybe some of you know some cool material that will show you how to properly create a shopping cart using the Composition API.

Thanks!

>Solution :

you need to set the ref value and also to parse the local storage value

let cartItems = ref([])
if (window.localStorage.getItem('CART') !== null) {
    cartItems.value = JSON.parse(window.localStorage.getItem('CART'));
}
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