Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect, useState } from "react";
- import { Box } from "@mui/material";
- export default function Solution() {
- const [items, setItems] = useState(["Book 1", "Book 2"]);
- const [quantities, setQuantities] = useState({});
- const [cart, setCart] = useState([]);
- // const options = ["one", "two"];
- // const[input, setInput] = React.useState("");
- // const[radio, setRadio] = React.useState("");
- // const[checkbox, setCheckbox] = React.useState(false);
- // const[select, setSelect] = React.useState("");
- useEffect(() => {
- console.log("quantities", quantities);
- }, [quantities]);
- useEffect(() => {
- console.log("cart", cart);
- }, [cart]);
- const addToCart = (item, quantity = 1) => {
- console.log(item, quantity);
- const index = cart.findIndex(cartItem => cartItem.name === item);
- let newCart = [...cart];
- if (index > -1) {
- newCart.splice(index, 1, { ...newCart[index], quantity: newCart[index]["quantity"] + quantity });
- // newCart = [
- // ...newCart.slice(0, index),
- // { ...newCart[index], quantity: newCart[index]["quantity"] + quantity },
- // ...newCart.slice(index + 1)
- // ];
- } else {
- newCart = [...newCart, { name: item, quantity: quantity }]
- }
- setCart(newCart);
- }
- return (
- <div style={{display: "flex", justifyContent: "center", alignItems: "center", height: "80vh"}}>
- <div
- // style={{ alignContent: "center"}}
- >
- {
- items.map(item => <div key={`item$${item}`}
- // style={{ display: "flex", alignItems: "center", height: "400px"}}
- >
- <label>{item}</label>
- <input type="number" value={quantities[item] ? parseInt(quantities[item]) : 1} onChange={e => setQuantities({ ...quantities, [item]: parseInt(e.target.value) })} />
- <button onClick={() => addToCart(item, quantities[item])}>{"Add to cart"}</button>
- </div>)
- }
- </div>
- </div>
- // <div>
- // {
- // items.map(item => (
- // <div key={item}>
- // <label>{item}</label>
- // <input
- // type="number"
- // value={quantities[item] !== undefined ? quantities[item] : 0}
- // onChange={e => {
- // let value = e.target.value;
- // // Use regex to remove leading zeros
- // let cleanedValue = value.replace(/^0+(?=\d)/, '');
- // // Handle empty input
- // setQuantities({ ...quantities, [item]: cleanedValue === '' ? '' : cleanedValue });
- // }}
- // />
- // </div>
- // ))
- // }
- // </div>
- // <div>
- // <input type="text" value={input} onChange={(e) => {console.log(e.target.value);setInput(e.target.value)}}/>
- // <input type="radio" value={"first"} onChange={(e) => setRadio(e.target.value)} checked={radio==="first"}/>
- // <input type="radio" value={"second"} onChange={(e) => setRadio(e.target.value)} checked={radio==="second"}/>
- // <label>{"Second"}</label>
- // <input type="checkbox" value={checkbox} onChange={(e) => setCheckbox(e.target.checked)}/>
- // <label>{"Third"}</label>
- // <label>{"Select"}</label>
- // <select value={select} onChange={e => setSelect(e.target.value)}>
- // <option value={""} disabled>{""}</option>
- // {
- // options.map(item => {return(
- // <option value={item}>{item}</option>
- // )})
- // }
- // </select>
- // <div>{`State: ${input} ${radio} ${checkbox} ${select}`}</div>
- // </div>
- );
- }
- /*
- import React from 'react';
- const PageComponent = React.memo(({ data }) => {
- return (
- <div>
- {data}
- </div>
- );
- });
- const App = () => {
- const [pages, setPages] = useState([]);
- const handleLoadMore = () => {
- // Fetch more data and update the pages state
- };
- return (
- <div>
- {pages.map((page, index) => (
- <PageComponent key={index} data={page} />
- ))}
- <button onClick={handleLoadMore}>Load More</button>
- </div>
- );
- };
- const fetchData = async (url) => {
- try {
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Response status: ${response.status}`);
- }
- const data = await response.json();
- return data;
- } catch (error) {
- setError(error);
- } finally {
- setLoading(false);
- }
- };
- const fetchAllData = async (items) => {
- try {
- const promises = items?.map((item) =>
- fetchData(`https://sample/api/breed/${item}/images/random`)
- );
- const imagesData = await Promise.all(promises);
- return imagesData;
- } catch (error) {
- setError(error);
- }
- };
- useEffect(() => {
- fetchData('https://sample/api/breeds/list/all').then((data) => {
- setData(data.message);
- fetchAllData(Object.keys(data?.message)).then((dataArray) => {
- setDataWithImages(dataArray);
- setLoading(false);
- });
- });
- }, []);
- const deleteData = async (id) => {
- try {
- const response = await fetch(
- 'https://api.sampleapis.com/countries/countries',
- {
- method: 'POST',
- headers: {
- // Accept: 'application/json',
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${token}`,
- },
- body: JSON.stringify({ id: id }),
- }
- );
- const data = await response.json();
- if (data.error != 200) {
- setDeleteError(data.message);
- }
- console.log(data);
- } catch (error) {
- setError(error);
- }
- };
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement