0
[
  { comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]

Above is my JSON Array that is stringified,I tried to JSON.parse and other functions like iterating it in a for loop but the key values also got scrambled.

Is there any way or an npm method that could instantly output the retrieved variable?

var cartItemFromLocalStorage = JSON.parse(localStorage.getItem("cartitem"));
if (cartItemFromLocalStorage != null) {
  console.log("It came defined");

  console.log("This is OG Array: " + cartItemFromLocalStorage);
  let cartItemObject = {
    //set object data
    comicid: this.state.comicId,
    purchasetype: this.state.purchaseType,
  };
  console.log(cartItemObject);
  cartItemFromLocalStorage.push(cartItemObject);
  localStorage.setItem("cartitem", result); //localstorage only supports strings
  toast.success("Item Added to cart");
} 

I checked the consoles and the states are putting up the data correctly.

I'm an extreme beginner in react js, help is much appreciated

4
  • 11
    Your input does not look like JSON, JSON requires "s around keys Commented Sep 8, 2020 at 2:04
  • 1
    Paste that into a json validator like jsonlint.com and it will confirm to you it is invalid Commented Sep 8, 2020 at 2:05
  • 1
    What is result in the following line: localStorage.setItem("cartitem", result);? Commented Sep 8, 2020 at 2:14
  • I'm sorry, it had been showing ever since, the google console had been showing as an Object, not as the real object, I just found it out on the application tab. thank youu Commented Sep 8, 2020 at 2:25

1 Answer 1

1

The "JSON" you have written is actually JavaScript, not JSON. To convert it JSON use the JSON.stringify function, like so

> JSON.stringify([
  { comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]);
'[{"comicid":"5f55e91271b808206c132d7c","purchasetype":"pb_single"}]'

and then replace the value in localStorage with it.

Even easier would be to type into the developer console

localStorage.setItem("cartitem", JSON.stringify([
  { comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.