Is there something wrong with the way I'm initializing my object and Array. I'm trying to save Cart data into the localStorage. I'm getting the data from the state, and it displays when I console. logged in, and the object seems to work but not the array, I don't understand what is wrong with the code.
Unhandled Rejection (TypeError): cartItemObjectArray.push is not a function
edit: however it seems that the if statement thinks that the local storage is not undefined even when it is, and I don't know how to resolve that too.
below is inside my constructor
constructor(props) {
super(props);
this.state = {
comicId: null,
selectedOption: null,
comicPrice: null,
purchaseType: null,
priceCurrency: "$",
currencyVisibility: null,
issueObjectState: null,
seriesObjectState: null,
pricingObjectState: null,
};
}
Below is my onSubmit() so that whenever te user hits add to cart the state values will be retrieved and set
onSubmit = async (event) => {
//submit function when adding item to cart
if (localStorage.getItem("cartitem") != undefined) {
//if there are items in the array then do this
console.log("It came not undefined");
let cartItemObjectArray = localStorage.getItem("cartitem");
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", cartItemObjectArray);
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
} else {
//if there are no items in the cart array in the local storage then initialize and do this
console.log("It came undefined");
let cartItemObjectArray = [];
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", cartItemObjectArray);
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
}
else if (cartItemFromLocalStorage == null) {
//if there are no items in the cart array in the local storage then initialize and do this
console.log("It came undefined");
let cartItemObjectArray = [];
let cartItemObject = {
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemObjectArray.push(cartItemObject);
localStorage.setItem("cartitem", JSON.stringify(cartItemObjectArray));
toast.success("Item Added to cart");
console.log("This is the mighty array ", cartItemObjectArray);
}
};
cartItem
inlocalStorage
is a string. So you need todeserialize
it withJSON.parse
first before adding items to the array