Skip to content Skip to sidebar Skip to footer

Objects Not Getting Passed Into Localstorage - React Js

So I'm trying to make a web application where it fetches data from backend API and displays it into frontend (This works) and also having add to cart functionality. I'm trying to s

Solution 1:

You need to store things in localStorage as a string. You also need to wait for the API response, axios.get returns a Promise.

asyncfunctionhandleClick(id) {
  try {
    const chosen_product = await axios.get(`http://localhost:8000/api/products/${id}`)
    setCart(cart + {chosen_product}) // This is wrong, can't add array to objectlocalStorage.setItem("cartItems", JSON.stringify(cart)) // This is wrong, cart will still be the previous value
  } catch (err) {
    console.error(err)
  }
}

In fact you already have this code structure in getProducts...

Also this code makes no sense:

setCart(cart + {chosen_product})

You can't add an object to an array.

Also setting cart straight after setCart won't work and cart will still be your previous value at that point, simplest solution is to create a variable for your new state.

const newCart = cart.concat(chosen_product);
setCart(newCart);
localStorage.setItem("cartItems", JSON.stringify(newCart));

Solution 2:

You need to make the object into a JSON string like so:

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

And you can then get the item and parse it like this:

JSON.parse(localStorage.getItem("cartItems"))

And you are back to a Javascript object.

Solution 3:

You need to store the object value after stringifying it.

storage.setItem(keyName, keyValue);

keyName A DOMString containing the name of the key you want to create/update.

keyValue A DOMString containing the value you want to give the key you are creating/updating.

Storing:

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

Retrieving:

const val = JSON.parse(localStorage.getItem("cartItems"))

Solution 4:

You need to stringify the object because

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

and you can parse the item to js object again using JSON.parse

JSON.parse(localStorage.getItem('cartItems'))

Post a Comment for "Objects Not Getting Passed Into Localstorage - React Js"