DEV Community

Saravanan Cn
Saravanan Cn

Posted on

Day 19: Using JSON.stringify() and JSON.parse() in My E-Commerce Project 🛒

Today, I continued improving my e-commerce website using HTML, CSS, and JavaScript.

I learned how to use JSON.stringify() and JSON.parse() with localStorage to store and retrieve cart data.

WHAT I LEARNED

1.JSON.stringify()

It converts my cart array into a JSON string so that I can store it in localStorage.

localStorage.setItem("cart", JSON.stringify(cart));Today, I continued improving my e-commerce website using HTML, CSS, and JavaScript.

I learned how to use JSON.stringify() and JSON.parse() with localStorage to store and retrieve cart data.

ringify(cart));

2.JSON.parse()

It converts the stored JSON string back into a JavaScript array.

let savedCart = JSON.parse(localStorage.getItem("cart"));

🛒 Applying it to my e-commerce website

When a user adds a product to the cart, I can save the updated cart:

cart.push(product);

localStorage.setItem("cart", JSON.stringify(cart));

When the page loads, I can restore the saved cart:

let cart = JSON.parse(localStorage.getItem("cart")) || [];

This allows the cart items to remain available after refreshing the page in the same browser.

Top comments (0)