selection not working in data grid, maybe it's not updating

13 views Asked by At

Im trying to add all the selections to the cart, but my selection seems to be emtpy. Like somehow the selection is not updating.

this part does not seem to be logging anything to console when i change the selection on then table.

is there something better i should be working then x-data-grid, they seem to have a pay version, but I have to pay to display a table, im new at this, but that seems odd.

          onSelectionModelChange={(newSelectionModel) => {
            console.log(newSelectionModel);
            console.log('Selection model:', newSelectionModel);
            console.log('Filtered data:', filteredData);
            setSelectedProducts(newSelectionModel);

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { DataGrid, GridToolbarContainer, GridToolbarFilterButton } from '@mui/x-data-grid';
import { Button, CssBaseline, Container, TextField, Select, MenuItem, Paper, List, ListItem, ListItemText } from '@mui/material';
import Cart from './cart'; // Import the Cart component
import './cart.css'; // Import the Cart CSS for styling


function CustomToolbar({ onFilterChange, onBcFilterChange }) {
  return (
    <GridToolbarContainer>
      <GridToolbarFilterButton />
      <Select
        defaultValue=""
        onChange={(e) => onFilterChange(e.target.value)}
        displayEmpty
        style={{ marginLeft: 8 }}
        inputProps={{ 'aria-label': 'Without label' }}
      >
        <MenuItem value="">All Terms</MenuItem>
        <MenuItem value="Monthly">Monthly</MenuItem>
        <MenuItem value="Annual">Annual</MenuItem>
        <MenuItem value="3 Year">3 Year</MenuItem>
      </Select>
      <Select
        defaultValue=""
        onChange={(e) => onBcFilterChange(e.target.value)}
        displayEmpty
        style={{ marginLeft: 8 }}
        inputProps={{ 'aria-label': 'Without label' }}
      >
        <MenuItem value="">All Billing Cycles</MenuItem>
        <MenuItem value="Monthly">Monthly</MenuItem>
        <MenuItem value="Annual">Annual</MenuItem>
        <MenuItem value="Triennial ">Triennial </MenuItem>
      </Select>
    </GridToolbarContainer>
  );
}

function App() {
  const [data, setData] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [filteredData, setFilteredData] = useState([]);
  const [termFilter, setTermFilter] = useState('');
  const [bcFilter, setbcFilter] = useState('');
  const [selectedProducts, setSelectedProducts] = useState([]);
  const [showCart, setShowCart] = useState(false);
  const [cartItems, setCartItems] = useState([]);


  useEffect(() => {
    axios.get('https://afa-cus-prod-cloudmoreclientapi.azurewebsites.net/api/getNCEskus?code=')
      .then(response => {
        if (response.data.length > 0) {
          const dataWithIdAndTerm = response.data.map((item, index) => ({
            ...item,
            id: item.RowKey || index,
            TermReadable: item.TERM === 'P1Y' ? 'Annual' : item.TERM === 'P1M' ? 'Monthly' : item.TERM === 'P3Y' ? '3 Year' : 'Unknown',
            
           // 'Product Name': item.Name, // Assuming 'Name' is the correct key for the product name
          }));
          setData(dataWithIdAndTerm);
          setFilteredData(dataWithIdAndTerm);
        }
      })
      .catch(error => console.error('There was an error!', error));
  }, []);

  useEffect(() => {
    let filtered = data.filter(item =>
      Object.keys(item).some(key =>
        String(item[key]).toLowerCase().includes(searchText.toLowerCase())
      )
    );

    if (termFilter) {
      filtered = filtered.filter(item => item.TermReadable === termFilter);
    }
    if (bcFilter) {
      filtered = filtered.filter(item => item['Billing Cycle'] === bcFilter);
    }


    setFilteredData(filtered);
  }, [searchText, data, termFilter,bcFilter]);

  const columns = [
    { field: 'Product Name', headerName: 'Product Name', width: 350,
    renderCell: (params) => (
      <div style={{ whiteSpace: 'normal', wordWrap: 'break-word', lineHeight: 'normal' }}>
        {params.value}
      </div>)},

{ field: 'TermReadable', headerName: 'TERM', width: 90 },
{ field: 'Billing Cycle', headerName: 'Billing', width: 90 },


    { field: 'SKU', headerName: 'SKU', width: 200 },
    { field: 'Price', headerName: 'Price', width: 75 },
    { field: 'Cost', headerName: 'Cost', width: 75 },
    
    
    // Add or adjust columns as needed
    {
      field: 'actions',
      headerName: 'Actions',
      sortable: false,
      width: 150,
      renderCell: (params) => {
        const onClick = (e) => {
          e.stopPropagation(); // don't select row after clicking
          const itemToAdd = data.find(item => item.id === params.id);
          handleAddToCart(itemToAdd);
        };
  
        return <Button onClick={onClick}>Add to Cart</Button>;
      }
    },
    { field: 'id', headerName: 'ID', width: 90, hide: true }
  ];


  const handleAddAllToCart = () => {
    const itemsToAdd = data.filter(product => selectedProducts.includes(product.id));
    const newCartItems = [...cartItems];
    console.log(itemsToAdd);
    console.log(selectedProducts);
  
    itemsToAdd.forEach(item => {
      const isItemInCart = newCartItems.some(cartItem => cartItem.id === item.id);
      if (!isItemInCart) {
        newCartItems.push(item);
      } else {
        console.log("Some items are already in the cart.");
      }
    });
  
    setCartItems(newCartItems);
    setShowCart(true);
  };


  const handleAddToCart = (itemToAdd) => {
    const isItemInCart = cartItems.some(item => item.id === itemToAdd.id);
  
    if (!isItemInCart) {
      setCartItems(prevItems => [...prevItems, itemToAdd]);
    } else {
      console.log("Item is already in the cart");
    }
  
    setShowCart(true);
  };

  const handleOpenCart = () => {
    const selectedItems = data.filter(product =>
      selectedProducts.includes(product.id)
    );
    setShowCart(true); // Show the cart with the selected items
  };

  return (
    <Container>
      <CssBaseline />
      <div style={{ height: 700, width: '100%', marginTop: 20 }}>
        <TextField
          variant="outlined"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          placeholder="Search…"
          style={{ marginBottom: '20px', marginRight: '8px' }}
        />
        <Button onClick={handleOpenCart} variant="contained" style={{ marginBottom: '20px' }}>
          View Cart
        </Button>
        <Button onClick={handleAddAllToCart} variant="contained" style={{ marginBottom: '20px', marginLeft: '8px' }}>
  Add All to Cart
</Button>
        <DataGrid
          rows={filteredData}
          columns={columns}
          pageSize={10}
          checkboxSelection
          disableSelectionOnClick={false}
          components={{
            Toolbar: CustomToolbar,
          }}
          componentsProps={{
            toolbar: { onFilterChange: setTermFilter,
              onBcFilterChange: setbcFilter},
      
          }}
          onSelectionModelChange={(newSelectionModel) => {
            console.log(newSelectionModel);
            console.log('Selection model:', newSelectionModel);
            console.log('Filtered data:', filteredData);
            setSelectedProducts(newSelectionModel);
          }}
          selectionModel={selectedProducts}
        />
      </div>
      // Inside your return statement in App component
<Cart items={cartItems} onClose={() => setShowCart(false)} show={showCart} />
    </Container>
    
  );
}

export default App;
0

There are 0 answers