0

I have a cart that prints out its data like this

(2) [{…}, {…}] 0:{data: "ids", description: "An apple iPhone 8", id: 2, image: "/images/3.jpg", name: "iPhone 8", price: 100, qty: 1} 1: {name: 'iPhone 7 +', description: 'An apple iPhone 7 plus', image: '/images/2.jpg', price: 120, id: 1, …}

but I want to alter it and add a cart id that I generate each time items are added to be like this

{ cart_id: uw8821jwsyhy29ki, 0:{data: "ids", description: "An apple iPhone 8", id: 2, image: "/images/3.jpg", name: "iPhone 8", price: 100, qty: 1} 1: {name: 'iPhone 7 +', description: 'An apple iPhone 7 plus', image: '/images/2.jpg', price: 120, id: 1, …}}

I am trying to create it like commerce js data, if you need the codes here it is

App.js

import React from 'react';
import { Navbar, Products, Cart, Checkout } from './components';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { CssBaseline } from '@material-ui/core';
import { products } from './components/Products/Product/ProductData';
import { useState } from 'react';

const App = () => {
  const [cart, setCart] = useState([]);
  const [order, setOrder] = useState({});
  const [errorMessage, setErrorMessage] = useState({});

  // const handleRemoveFromCart = (id) =>{
  //   const newItems = item.filter(item => item.id != id)
  //   setCart(newItems);
  // }
  const onAdd = (product) => {
    const exist = cart.find((x) => x.id === product.id);
    if (exist) {
      setCart(
        cart.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x
        )
      );
    } else {
      setCart([...cart, { ...product, qty: 1 }]);
    }
  };
  const onRemove = (product) => {
    const exist = cart.find((x) => x.id === product.id);
    if (exist.qty === 1) {
      setCart(cart.filter((x) => x.id !== product.id));
    } else {
      setCart(
        cart.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty - 1 } : x
        )
      );
    }
  };
  const cartRemove = (product) => {
    const exist = cart.find((x) => x.id === product.id);
    if (exist.qty) {
      setCart(cart.filter((x) => x.id !== product.id));
    } else {
      setCart(
        cart.map((x) =>
          x.id === product.id ? { ...exist, qty: 0 } : x
        )
      );
    }
  };
  const cartEmpty = () => setCart([]);

  const handleCaptureCheckout = (newOrder) => {
    try {
      const incomingOrder  = newOrder;
      setOrder(incomingOrder);

      cartEmpty();
    } catch (error) {
      setErrorMessage(error.message);
    }
  }
  return (
    <Router>
      <div>
        <CssBaseline />
        <Navbar countCartItems={cart.length}/>
        <Switch>
          <Route exact path="/">
            <Products onAdd={onAdd} products={products} />
          </Route>
          <Route path="/cart">
            <Cart cartEmpty={cartEmpty} cartRemove={cartRemove} onAdd={onAdd} cart={cart} onRemove={onRemove} />
          </Route>
          <Route path="/checkout">
            <Checkout cart={cart} order={order} error={errorMessage} onCaptureCheckout={handleCaptureCheckout} />
          </Route>
        </Switch>
      </div>
    </Router>
  );
};

export default App;

Cart.js

import React from 'react'
import { Container, Typography, Button, Grid } from '@material-ui/core';
import CartItems from './CartItems/CartItems';
import useStyles from './styles';
import { Link } from 'react-router-dom';


const Cart = ({ cart, onAdd, onRemove, cartRemove, cartEmpty }) => {

    const classes = useStyles();
    console.log(cart);
    const itemsPrice = cart.reduce((a, c) => a + c.qty * c.price, 0);
    const totalPrice = itemsPrice;
      function generate_token(length){
    var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".split("");
    var b = [];  
    for (var i=0; i<length; i++) {
        var j = (Math.random() * (a.length-1)).toFixed(0);
        b[i] = a[j];
    }
    return b.join("");
  }
  
    const prods = (cart) => ({cartid: `${'KLIN_321'+generate_token(12)}`},
    {
      ...cart,
      cartid: `${'KLIN_321'+generate_token(12)}`
      // value: `${o.account_title_id} - ${o.detailed_id} - ${o.currency_id}`,
    });
    console.log(prods);
    return (
        <Container>
          <div className={classes.toolbar} />
          <Typography className={classes.title} variant="h3" gutterBottom>Your Shopping Cart</Typography>
          {cart.length === 0 && 
          <Typography variant="subtitle1">You have no items in your shopping cart,
            <Link className={classes.link} to="/">start adding some</Link>!
          </Typography>}
          <>
            <Grid container spacing={3}>
              {cart.map((item) => (
                <Grid item xs={12} sm={4} key={item.id}>
                  <CartItems cartRemove={cartRemove} onAdd={onAdd} onRemove={onRemove} item={item} />
                </Grid>
              ))}

            </Grid>
            {cart.length !== 0 && (
              <div className={classes.cardDetails}>
                <Typography variant="h4">Subtotal: ${totalPrice.toFixed(2)}</Typography>
                <div>
                  <Button className={classes.emptyButton} size="large" type="button" variant="contained" onClick={() => cartEmpty(cart)} color="secondary">Empty cart</Button>
                  <Button cart={cart} className={classes.checkoutButton} component={Link} to="/checkout" size="large" type="button" variant="contained" color="primary">Checkout</Button>
                </div>
              </div>
            )}
          </>
        </Container>
      );
}

export default Cart

ProductData.js that supplies the product for the cart

export const products = [
    {
      name: 'iPhone 11',
      description: "A light green apple iPhone 11",
        image: '/images/1.jpg',
        price: 400,
      id: 0,
      data: 'ids',
    },
    {
      name: 'iPhone 7 +',
      description:"An apple iPhone 7 plus",
      image: '/images/2.jpg',
      price: 120,
      id: 1,
      data: 'ids',
    },
    {
      name: 'iPhone 8',
      description:"An apple iPhone 8",
      image: '/images/3.jpg',
      price: 100,
      id: 2,
      data: 'ids',
    },
    {
        name: 'Samsung Note 21',
        description:"A black Samsung galaxy note 21",
        image: '/images/4.jpg',
        price: 850,
        id: 3,
        data: 'ids',
      },
      {
        name: 'Samsung S9 plus',
        description:"A black Samsung galaxy S9 Plus",
        image: '/images/5.jpg',
        price: 650,
        id: 4,
        data: 'ids',
      },
      {
        name: 'Iphone 11 pro max',
        description:"A white Iphone 11 pro max",
        image: '/images/6.jpg',
        price: 800,
        id: 5,
        data: 'ids',
      },
      {
        name: 'Apple Watch',
        description:"An apple watch different colors available",
        image: '/images/7.jpg',
        price: 90,
        id: 6,
        data: 'ids',
      },
      {
        name: 'Apple Watch',
        description:"An apple watch different colors available",
        image: '/images/8.jpg',
        price: 10,
        id: 7,
        data: 'ids',
      },
      {
        name: 'Apple airpods casing',
        description:"A white apple airpods casing",
        image: '/images/9.jpg',
        price: 10,
        id: 8,
        data: 'ids',
      },
      {
        name: 'Gym Website',
        description:"A prototype of a gym website that displaying the members, coaches, programs, our pricing plans and how to contact us, with a counting animation and a working email join using email js.",
        image: '/images/10.jpg',
        price: 10,
        id: 9,
        data: 'ids',
      },
      {
        name: 'Gym Website',
        description:"A prototype of a gym website that displaying the members, coaches, programs, our pricing plans and how to contact us, with a counting animation and a working email join using email js.",
        image: '/images/11.jpg',
        price: 10,
        id: 10,
        data: 'ids',
      },
      {
        name: 'Gym Website',
        description:"A prototype of a gym website that displaying the members, coaches, programs, our pricing plans and how to contact us, with a counting animation and a working email join using email js.",
        image: '/images/12.jpg',
        price: 10,
        id: 11,
        data: 'ids',
      },
  ];

if it is possible to change the cart the initial ids example the 0 before the data: ids to line_items before

(2) [{…}, {…}] 0:{data: "ids", description: "An apple iPhone 8", id: 2, image: "/images/3.jpg", name: "iPhone 8", price: 100, qty: 1}
(2) [{…}, {…}] line_items:{data: "ids", description: "An apple iPhone 8", id: 2, image: "/images/3.jpg", name: "iPhone 8", price: 100, qty: 1}
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    Your cart is an Array, and so the indexes are numeric as expected (`0: ...`). If you want to use `line_items` as the key, you probably want to convert the cart to an Object. – filipe Sep 09 '22 at 19:46
  • How do I convert it from array to object pls tell me – Samuel Paschalson Sep 09 '22 at 23:13

1 Answers1

2

The comment above is correct. You just need to convert the array to an object. You could try something like this where you spread the array into an object though there are many ways you could do it:

let cart = [{
    description: "An apple iPhone 8",
    id: 2,
    image: "/images/3.jpg",
    name: "iPhone 8",
    price: 100,
    qty: 1
  },
  {
    name: 'iPhone 7 +',
    description: 'An apple iPhone 7 plus',
    image: '/images/2.jpg',
    price: 120,
    id: 1,
    qty: 2
  }
]

let newCart = {...cart};

newCart["cart_id"] = "SomeCartId";

console.log(newCart);

Here is a helpful answer on converting arrays to objects.

JBrown
  • 825
  • 6
  • 22