Not able to delete selected row in react material table

89 Views Asked by At

So I have created a react material table and I am able to fetch data using axios as third party library but when i am implementing delete api to delete the selected row which i have selected using checkbox i am not able to delete the the row and I have console it in browser and its showing no row is selected

And here is my complete code

import { useEffect, useRef, useState, useMemo } from "react";
import {
  MaterialReactTable,
  useMaterialReactTable,
} from "material-react-table";
import { Checkbox } from "@mui/material";
import axiosInstance from "../apiConfig";

const Example = () => {
  // Data and fetching state
  const [data, setData] = useState([]);
  const [isError, setIsError] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefetching, setIsRefetching] = useState(false);
  const [rowCount, setRowCount] = useState(0);

  // Selected rows for delete
  const selectedRows = useRef([]); 

  // Table state
  const [columnFilters, setColumnFilters] = useState([]);
  const [globalFilter, setGlobalFilter] = useState("");
  const [sorting, setSorting] = useState([]);
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });

  // Handle selection
  const handleRowSelection = (row, isChecked) => {
    const existingIndex = selectedRows.current.findIndex(
      (selectedRow) => selectedRow.sku_id === row.sku_id
    );

    if (isChecked) {
      if (existingIndex === -1) {
        selectedRows.current = [...selectedRows.current, row];
      }
    } else {
      if (existingIndex !== -1) {
        selectedRows.current.splice(existingIndex, 1);
      }
    }
  };

  // Handle delete
  const handleDeleteSelected = async () => {
    if (window.confirm("Are you sure you want to delete the selected rows?")) {
      const deletedIds = selectedRows.current.map((row) => row.sku_id);

      if (deletedIds.length > 0) {
        try {
          const response = await axiosInstance.delete("/SKU", {
            data: { ids: deletedIds },
          });

          if (response.status === 200) {
            // Update UI after successful deletion
            const updatedData = data.filter(
              (row) => !deletedIds.includes(row.sku_id)
            );

            setData(updatedData);
            setRowCount(rowCount - deletedIds.length);
          }

          selectedRows.current = [];
        } catch (error) {
          setIsError(true);
          console.error(error);
        }
      } else {
        // If no rows are selected, show an alert or handle this scenario
        console.log("No rows selected for deletion");
      }
    }
  };

  // Update data based on filters and sorting (same as before)

  useEffect(() => {
    const fetchData = async () => {
      // ... fetch data logic
      if (!data.length) {
        setIsLoading(true);
      } else {
        setIsRefetching(true);
      }

      const url = new URL(
        "http://localhost:7101/api/sku"
        // "/api/data",
        // process.env.NODE_ENV === "production"
        //   ? "https://www.material-react-table.com"
        //   : "http://localhost:7101"
      );
      url.searchParams.set(
        "start",
        `${pagination.pageIndex * pagination.pageSize}`
      );
      url.searchParams.set("size", `${pagination.pageSize}`);
      url.searchParams.set("filters", JSON.stringify(columnFilters ?? []));
      url.searchParams.set("globalFilter", globalFilter ?? "");
      url.searchParams.set("sorting", JSON.stringify(sorting ?? []));

      try {
        const response = await axiosInstance("/SKU");
        // const json = await response.json();
        const responsedata = response.data;
        setData(responsedata.result);
        setRowCount(responsedata.result.length);
      } catch (error) {
        // ... error handling
      }
      setIsError(false);
      setIsLoading(false);
      setIsRefetching(false);
    };
    fetchData();
  }, [
    columnFilters,
    data.length,
    globalFilter,
    pagination.pageIndex,
    pagination.pageSize,
    sorting,
  ]);

  // Table columns
  const columns = useMemo(
    () => [
      // ... your existing columns
      {
        accessorKey: "checkbox",
        header: "",
        renderCell: (row) => (
          <Checkbox
            checked={selectedRows.current.includes(row)}
            onChange={(e) => handleRowSelection(row, e.target.checked)}
          />
        ),
      },
      {
        accessorKey: "sku_id",
        header: "SKU ID",
      },

      {
        accessorKey: "description",
        header: "Description",
      },
      {
        accessorKey: "su",
        header: "SU",
      },
      {
        accessorKey: "hu",
        header: "Hu",
      },
      {
        accessorKey: "batch_no",
        header: "Batch",
      },
    ],
    []
  );

  const table = useMaterialReactTable({
    columns,
    data,
    enableRowSelection: true,
    getRowId: (row) => row.id,
    initialState: { showColumnFilters: true },
    manualFiltering: true,
    manualPagination: true,
    manualSorting: true,
    muiToolbarAlertBannerProps: isError
      ? {
          color: "error",
          children: "Error loading data",
        }
      : undefined,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onPaginationChange: setPagination,
    onSortingChange: setSorting,
    rowCount,
    state: {
      columnFilters,
      globalFilter,
      isLoading,
      pagination,
      showAlertBanner: isError,
      showProgressBars: isRefetching,
      sorting,
    },
  });

  return (
    <>
      <button onClick={handleDeleteSelected}>Delete Selected</button>
      <MaterialReactTable table={table} />;
    </>
  );
};

export default Example;
0

There are 0 best solutions below