Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly.

This issue arose after deploying the website on Vercel. Storing "cart" as a string rather than an object is leading to errors.

You can visit the site here:

@Yogi expressed concerns that my initial explanation was insufficient. The cart object is initially created within the addToCart method... When there are no items in the cart, it creates the cart object with the key item code and values such as quantity, price, name, size, variant...

if (itemCode in cart) {
      newCart[itemCode].qty = cart[itemCode].qty + qty

    }
    else {
      newCart[itemCode] = { qty: 1, price, name, size, variant }
    }

After deployment on Vercel, the JSON.stringify converted "cart" in the local storage as depicted in the image below..

Here is the code snippet:

const [cart, setCart] = useState({})

 const [subTotal, setSubTotal] = useState(0)

  useEffect(() => {

try {
  if (localStorage.getItem("cart")) {
    setCart(JSON.parse(localStorage.getItem("cart")));   
    saveCart(JSON.parse(localStorage.getItem("cart"))); 
  }

} 
catch (error) {
  console.error(error);
  localStorage.clear;
}
}, [])

 const saveCart = (myCart) => {

    localStorage.setItem("cart",JSON.stringify(myCart))
    let subt = 0;
    
    let keys = Object.keys(myCart)

    for (let index = 0; index < keys.length; index++) {
      subt += myCart[keys[index]].qty * myCart[keys[index]].price
    }
    setSubTotal(subt)
  }

  const addToCart = (itemCode, qty, price, name, size, variant) => {
    let newCart = cart;

    if (itemCode in cart) {
      newCart[itemCode].qty = cart[itemCode].qty + qty

    }
    else {
      newCart[itemCode] = { qty: 1, price, name, size, variant }
    }


    setCart(newCart);
    saveCart(newCart);
  }

https://i.sstatic.net/Q3MpX.png

Answer №1

I decided to try opening the link in an incognito window, and to my surprise, the problem disappeared. Could it be that having the same object for both my local host and deployed site is causing the issue?

Answer №2

Within the confines of localStorage, data is stored as strings, regardless of its original format as an object. To access it in its intended form, parsing is required to convert it back into an object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The 'ascii' codec is unable to encode the character because its ordinal value is outside the range of 0-127

Currently, I am utilizing selenium and beautifulsoup to scrape various webpages. Within this process, I am iterating through multiple links, extracting information, and storing it in a JSON format: for event in events: case = {'Artist': item ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

Utilize Express.js to seamlessly stream and process uploaded files with formidable and gm, ensuring a streamlined process without

I am looking for a solution to upload and resize an image in one step without having to write to disk twice. For uploading images, I am using: node-formidable: https://github.com/felixge/node-formidable And for resizing the images, I am using: gm: Howev ...

Tips for creating a JSON value without a property name

In order to generate JSON output without property names for DataTables (datatables.net) in the browser, I am faced with the following format requirement: { "aaData": [ [ "Trident", "Internet Explorer 4.0", " ...

Modifying the JSON output of a web API

After creating an API in visual studio 2015, I noticed that while running the API, it provides me with the expected response and data. Below you can find my controller code: public HttpResponseMessage GetByMsn(string msn, DateTime dt) { try ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

How can I show the real width of an image on a mobile device?

I have integrated the infinite slide plugin from jQueryscript.net into my website. While it works perfectly on desktop with background images, I am facing an issue on mobile devices where the image width needs to be displayed in full. I attempted to adjust ...

What is the best way to fetch HTML content using JavaScript?

I needed to incorporate JavaScript for fetching HTML code. I structured the HTML code in the following manner; <html> <div id="tesingCode"> <h1>Title</h1> <p>testOfCodetestOfCodetestOfCodetestOfCode</p> </div ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

"PHP and jQuery, a winning combination for handling form

I have recently begun working on the form below and I have a couple of inquiries: Firstly, how could I utilize PHP or Local Storage to store the data from the previous page when the user clicks 'next'? Secondly, is there a way to attach an imag ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

Exploring Error Handling in AngularJS and How to Use $exceptionHandler

When it comes to the documentation of Angular 1 for $exceptionHandler, it states: Any uncaught exception in angular expressions is passed to this service. https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler However, I have noticed ...

What is the significance of having a timer in a Redux reducer to prompt a re-rendering process?

Encountered some unusual behavior that I need to understand better Here is the code for my reducer. Strangely, the component linked to the redux state does not re-render with this code. Despite confirming through developer tools that the state updates cor ...

What are the different ways to switch between options in npx create-react-app?

I am currently in the process of building a fresh NextJs app. I have utilized the npm create-react-app command, and upon completion, the console is displaying Yes/No options with each question having either Yes or No highlighted. Is there a method to swit ...

Determine the vertical dimension of a child division once it has been integrated into an HTML document

My goal is to create a website with multiple pages without having to recreate the toolbar for each page. To achieve this, I have created a separate HTML file and CSS file specifically for the toolbar. On each page, I simply import the toolbar using the fo ...

Can you explain the functionality of the return false statement within the validate plugin's submitHandler

While exploring the validator plugin examples, I stumbled upon a code snippet online: $('#testimonials-form').validate({ rules: { "t-title": { required: true, minlength: 5 }, "t-text": { ...

Please be patient until setInterval() completes its task

In order to add a dice-rolling effect to my Javascript code, I am considering using the setInterval() method. To test this out, I have come up with the following code: function rollDice() { var i = Math.floor((Math.random() * 25) + 5); var j = i; ...

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

Combining HTML template and queryset into a JSON ajax response in Django

I need my view to return the page content and certain parameters for use in the success function of Ext.Ajax.request. views.py def importFile(request): form = ImportVectorForm() html_response = render_to_response("page_content.html", {'form& ...