I have a REACT JS Client side where I want to save Shopping Cart items in localStorage by using push method. I have an AddtoCart function which will Push the product details array of the product which is clicked, to localStorage JSON object CartObj.
But what I want is to have the entire CartObj of localStorage in a JSON Object format in which Products are grouped according to their CompanyNames (instead of just simple Strings).
When I Click "AddtoCart" button Im sending a single Product details in this format:
{
"SparePartID":"45",
"Name":"Lights",
"Price":"2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
}
And what I want is to push this above item in CartObj JSON object in localStorage (CartObj is currently empty). And whenever any item is clicked, its data is pushed to the same CartObj. But I want to get this below format of data in my localStroage CartObj after few items are pushed in it. (items grouped by CompanyNames).
{
"records": {
"Master Automotives": [
{
"SparePartID": "43",
"Name": "Oil and Lubricants",
"Price": "4500",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
},
{
"SparePartID": "45",
"Name": "Lights",
"Price": "2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "2300"
}
],
"Repair Solutions": [
{
"SparePartID": "47",
"Name": "Steering Wheel",
"Price": "1500",
"VendorID": "60",
"CompanyName": "Repair Solutions",
"Qty": 1,
"TotalPrice": "1500"
}
],
"FiveStar Automotives": [
{
"SparePartID": "51",
"Name": "Brakes",
"Price": "234",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "234"
},
{
"SparePartID": "53",
"Name": "Clutch",
"Price": "999",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "999"
},
{
"SparePartID": "55",
"Name": "LED",
"Price": "288",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "288"
}
]
}
}
CAN I DO IT by push method in localStroage or is there any other way to save data in localStorage in this format. I want this format coz I need to handle order placement of these products separately.
here is my ADdToCart method in REACT:
AddToC(part){
console.log("PartID to be added in cart: ", part); //this part shows details of a product in format I mentioned on very top.
const alreadyInCart = JSON.stringify(localStorage.getItem('cartObj'));
alreadyInCart.push(part);
}
EDIT:
{this.state.spareParts.map((part, index) =>
<div>
<h4 > {part.Name} </h4>
<h5> Rs. {part.Price} </h5>
<h5> {part.CompanyName} </h5>
<div>
<button onClick={() => this.AddToCart(index, part.SparePartID)}
Add to Cart
</button>
</div>
)}
records, on state component ?const unsub = store.subscribe(() => localStorage.setItem("languages", JSON.stringify(store.getState().languages)) );A simple example, how to store using redux, maybe you are saving the incorrect Object. try to save therecords.records, can you share your code ?