add products to cart

 avatar
unknown
plain_text
2 years ago
5.3 kB
3
Indexable
import "./styles.css";
import { useEffect, useState } from "react";
import Autocomplete from "@mui/material/Autocomplete";
import { Box, Button, TextField, Typography } from "@mui/material";

const App = () => {
  const [fruits, setFruits] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  const [addedFruits, setAddedFruits] = useState([]);
  const [selectedFruit, setSelectedFruit] = useState(null);
  const [fruitsAmount, setFruitsAmount] = useState({});

  const handleAddFruit = () => {
    if (selectedFruit) {
      const { id } = selectedFruit;
      setAddedFruits((prev) => [...prev, selectedFruit]);
      setFruitsAmount((prevAmounts) => ({
        ...prevAmounts,
        [id]: prevAmounts[id] ? prevAmounts[id] + 1 : 1 // Preserve existing fruitAmount if it already exists, otherwise set it to 1
      }));
      setSelectedFruit(null);
      setSearchValue("");
    }
  };

  const handleInputChange = (event, value) => {
    setSearchValue(value);
  };

  useEffect(() => {
    fetch("https://fruityvice.com/api/fruit/all")
      .then((response) => response.json())
      .then((data) => setFruits(data))
      .catch((error) => console.error("Error fetching fruits:", error));
  }, []);

  useEffect(() => {
    const initialAmounts = {};
    addedFruits.forEach(({ id }) => {
      if (fruitsAmount[id] === 0) {
        return null;
      }
      if (!fruitsAmount[id]) {
        // Preserve existing fruitAmount if it already exists
        initialAmounts[id] = 1;
      } else {
        initialAmounts[id] = fruitsAmount[id];
      }
    });
    setFruitsAmount(initialAmounts);
  }, [addedFruits]);

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        m: 5
      }}
    >
      <Typography
        variant="h2"
        style={{ textAlign: "center", marginBottom: 15 }}
      >
        Add products
      </Typography>
      <Box display="flex" width="100%" alignItems="end" mb={2}>
        <Autocomplete
          options={fruits}
          getOptionLabel={(fruit) => fruit.name}
          fullWidth
          value={selectedFruit}
          onChange={(event, newValue) => {
            setSelectedFruit(newValue);
          }}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Product"
              placeholder="e.g. Product ABC"
              variant="outlined"
              onChange={handleInputChange}
              value={searchValue}
              fullWidth
            />
          )}
        />
        <Button
          onClick={handleAddFruit}
          variant="contained"
          color="primary"
          sx={{ height: "56px" }}
        >
          Add
        </Button>
      </Box>
      {addedFruits.map(({ name, id }) => {
        const fruitAmount = fruitsAmount[id]; // Get the fruitAmount from the state or default to 1
        const handleDecrease = () => {
          setFruitsAmount((prevAmounts) => {
            const newAmounts = {
              ...prevAmounts,
              [id]: Math.max((prevAmounts[id] || 1) - 1, 0) // Decrease the fruitAmount, but ensure it doesn't go below 0
            };

            // Check if the fruitAmount is 0, and remove the product from addedFruits and newAmounts
            if (newAmounts[id] === 0) {
              setAddedFruits((prevFruits) =>
                prevFruits.filter((fruit) => fruit.id !== id)
              );
              delete newAmounts[id];
            }

            return newAmounts;
          });
        };

        return (
          <Box
            sx={{
              border: "2px solid #F4F4F4",
              width: "100%",
              height: "72px",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              m: 1
            }}
            key={id}
          >
            <Typography sx={{ p: 2 }}>{name}</Typography>
            <Box display="flex" alignItems="center">
              <Button onClick={handleDecrease}>-</Button>
              <Typography
                sx={{
                  width: "27px",
                  height: "27px",
                  backgroundColor: "common.gray",
                  textAlign: "center"
                }}
              >
                {fruitAmount}
              </Typography>
              <Button
                onClick={() =>
                  setFruitsAmount((prevAmounts) => ({
                    ...prevAmounts,
                    [id]: (prevAmounts[id] || 1) + 1
                  }))
                }
              >
                +
              </Button>
            </Box>
          </Box>
        );
      })}

      {addedFruits.length === 0 && (
        <Box
          sx={{
            height: "100vh",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <img
            style={{
              width: "60px",
              height: "60px"
            }}
            src="/images/image 1.png"
            alt="No products"
          />
          <Typography mt={2}>No products have been added.</Typography>
        </Box>
      )}
    </Box>
  );
};

export default App;