Advertisement
amt

Cart

amt
Oct 22nd, 2024 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useEffect, useState } from "react";
  2. import { Box } from "@mui/material";
  3.  
  4. export default function Solution() {
  5.  
  6.     const [items, setItems] = useState(["Book 1", "Book 2"]);
  7.     const [quantities, setQuantities] = useState({});
  8.     const [cart, setCart] = useState([]);
  9.  
  10.  
  11.  
  12.     // const options = ["one", "two"];
  13.  
  14.     // const[input, setInput] = React.useState("");
  15.     // const[radio, setRadio] = React.useState("");
  16.     // const[checkbox, setCheckbox] = React.useState(false);
  17.     // const[select, setSelect] = React.useState("");
  18.  
  19.  
  20.  
  21.     useEffect(() => {
  22.         console.log("quantities", quantities);
  23.     }, [quantities]);
  24.  
  25.     useEffect(() => {
  26.         console.log("cart", cart);
  27.     }, [cart]);
  28.  
  29.  
  30.     const addToCart = (item, quantity = 1) => {
  31.         console.log(item, quantity);
  32.  
  33.         const index = cart.findIndex(cartItem => cartItem.name === item);
  34.  
  35.         let newCart = [...cart];
  36.  
  37.         if (index > -1) {
  38.             newCart.splice(index, 1, { ...newCart[index], quantity: newCart[index]["quantity"] + quantity });
  39.  
  40.             // newCart = [
  41.             //     ...newCart.slice(0, index),
  42.             //     { ...newCart[index], quantity: newCart[index]["quantity"] + quantity },
  43.             //     ...newCart.slice(index + 1)
  44.             // ];
  45.         } else {
  46.             newCart = [...newCart, { name: item, quantity: quantity }]
  47.         }
  48.  
  49.         setCart(newCart);
  50.     }
  51.  
  52.     return (
  53.         <div style={{display: "flex", justifyContent: "center", alignItems: "center", height: "80vh"}}>
  54.             <div
  55.             // style={{ alignContent: "center"}}
  56.             >
  57.             {
  58.                 items.map(item => <div key={`item$${item}`}
  59.                     // style={{ display: "flex", alignItems: "center", height: "400px"}}
  60.                 >
  61.                     <label>{item}</label>
  62.                     <input type="number" value={quantities[item] ? parseInt(quantities[item]) : 1} onChange={e => setQuantities({ ...quantities, [item]: parseInt(e.target.value) })} />
  63.                     <button onClick={() => addToCart(item, quantities[item])}>{"Add to cart"}</button>
  64.                 </div>)
  65.             }
  66.             </div>
  67.         </div>
  68.         // <div>
  69.         //     {
  70.         //         items.map(item => (
  71.         //             <div key={item}>
  72.         //                 <label>{item}</label>
  73.         //                 <input
  74.         //                     type="number"
  75.         //                     value={quantities[item] !== undefined ? quantities[item] : 0}
  76.         //                     onChange={e => {
  77.         //                         let value = e.target.value;
  78.  
  79.         //                         // Use regex to remove leading zeros
  80.         //                         let cleanedValue = value.replace(/^0+(?=\d)/, '');
  81.  
  82.         //                         // Handle empty input
  83.         //                         setQuantities({ ...quantities, [item]: cleanedValue === '' ? '' : cleanedValue });
  84.         //                     }}
  85.         //                 />
  86.         //             </div>
  87.         //         ))
  88.         //     }
  89.         // </div>
  90.  
  91.         //     <div>
  92.         //     <input type="text" value={input} onChange={(e) => {console.log(e.target.value);setInput(e.target.value)}}/>
  93.         //     <input type="radio" value={"first"} onChange={(e) => setRadio(e.target.value)} checked={radio==="first"}/>
  94.         //     <input type="radio" value={"second"} onChange={(e) => setRadio(e.target.value)} checked={radio==="second"}/>
  95.         //     <label>{"Second"}</label>
  96.         //     <input type="checkbox" value={checkbox} onChange={(e) => setCheckbox(e.target.checked)}/>
  97.         //     <label>{"Third"}</label>
  98.         //     <label>{"Select"}</label>
  99.         //     <select value={select} onChange={e => setSelect(e.target.value)}>
  100.         //     <option value={""} disabled>{""}</option>
  101.         //         {
  102.         //             options.map(item => {return(
  103.         //                 <option value={item}>{item}</option>
  104.         //             )})
  105.         //         }
  106.  
  107.         //     </select>
  108.  
  109.         //     <div>{`State: ${input} ${radio} ${checkbox} ${select}`}</div>
  110.  
  111.         // </div>
  112.  
  113.     );
  114. }
  115.  
  116. /*
  117. import React from 'react';
  118.  
  119. const PageComponent = React.memo(({ data }) => {
  120.     return (
  121.         <div>
  122.             {data}
  123.         </div>
  124.     );
  125. });
  126.  
  127. const App = () => {
  128.     const [pages, setPages] = useState([]);
  129.  
  130.     const handleLoadMore = () => {
  131.         // Fetch more data and update the pages state
  132.     };
  133.  
  134.     return (
  135.         <div>
  136.             {pages.map((page, index) => (
  137.                 <PageComponent key={index} data={page} />
  138.             ))}
  139.             <button onClick={handleLoadMore}>Load More</button>
  140.         </div>
  141.     );
  142. };
  143.  
  144. const fetchData = async (url) => {
  145.         try {
  146.             const response = await fetch(url);
  147.             if (!response.ok) {
  148.                 throw new Error(`Response status: ${response.status}`);
  149.             }
  150.             const data = await response.json();
  151.             return data;
  152.         } catch (error) {
  153.             setError(error);
  154.         } finally {
  155.             setLoading(false);
  156.         }
  157.     };
  158.  
  159.     const fetchAllData = async (items) => {
  160.         try {
  161.             const promises = items?.map((item) =>
  162.                 fetchData(`https://sample/api/breed/${item}/images/random`)
  163.             );
  164.             const imagesData = await Promise.all(promises);
  165.             return imagesData;
  166.         } catch (error) {
  167.             setError(error);
  168.         }
  169.     };
  170.  
  171.     useEffect(() => {
  172.         fetchData('https://sample/api/breeds/list/all').then((data) => {
  173.             setData(data.message);
  174.             fetchAllData(Object.keys(data?.message)).then((dataArray) => {
  175.                 setDataWithImages(dataArray);
  176.                 setLoading(false);
  177.             });
  178.         });
  179.     }, []);
  180.  
  181. const deleteData = async (id) => {
  182.     try {
  183.       const response = await fetch(
  184.         'https://api.sampleapis.com/countries/countries',
  185.         {
  186.           method: 'POST',
  187.           headers: {
  188.             // Accept: 'application/json',
  189.             'Content-Type': 'application/json',
  190.             'Authorization': `Bearer ${token}`,
  191.           },
  192.           body: JSON.stringify({ id: id }),
  193.         }
  194.       );
  195.       const data = await response.json();
  196.       if (data.error != 200) {
  197.         setDeleteError(data.message);
  198.       }
  199.       console.log(data);
  200.     } catch (error) {
  201.       setError(error);
  202.     }
  203.   };
  204. */
  205.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement