1

I am calling "deleteDepartment" function on a button to delete the department rows from my table. And from the table (I'm using shancn table which use tanstack table) to get the selected row index in "selectedRows" hook (setSelectedRows is passed as prop to the table component which gets the value from rowSelection hooks in the table).

The problem is: I am able to delete the first two or three rows without any problem, but as I continue, "rowSelection" state saves the value from previous function call and it adds to the current selected row array.

Example: if I deleted row ['1'], the next time I click the button to delete row 2, the. value of "rowSelection" should be just ['2'] but it added to the previous value like ['1','2'].

I'm lost as to why is this behaviour occurs. I thought it can be due to closure and async nature hence the reason why I use useCallback hook, but no use. Someone with better knowledge please help

const DepartmentsAndRolesPage = () => {
  const [departments, setDepartments] = useState<departmentTypes[]>([]);
  const [selectedRows, setSelectedRows] = useState({});
  const [rowIndexes, setRowIndexes] = useState<string[]>([]);

  useEffect(() => {
    getDepartment();
  }, []);

  useEffect(() => {
    const indexesToAdd = Object.keys(selectedRows);
    setRowIndexes(indexesToAdd);
  }, [selectedRows]);

  const deleteDepartment = useCallback(async () => {

    if (rowIndexes.length === 0) {
      return;
    }

    if (rowIndexes.length === 1) {
      const filteredDepartment = departments[parseInt(rowIndexes[0])];
      const id = filteredDepartment._id;
      const response = await axios.delete(`/api/department/delete/${id}`);
      if (response.statusText === "OK") {
        getDepartment();
        setSelectedRows({});
      }
      return;
    }

    if (rowIndexes.length > 1) {
      const departmentsToDelete = rowIndexes.map(
        (rowIndex) => departments[parseInt(rowIndex)]._id
      );
      const response = await axios.post("/api/department/delete", {
        _id: departmentsToDelete,
      });
      if (response.statusText === "OK") {
        getDepartment();
        setSelectedRows({});
      }
      return;
    }
  }, [departments, rowIndexes, toast]);
Return (rest of the UI code here.... )

ANSWER

I still do not know why react behaved that way, instead I work around to find the solution.

Instead of getting the row index (the index of the row) from the dataTable, I used the id of each item in the row. That solved the issue.

yanger rai
  • 102
  • 9

1 Answers1

0

You should set the rowIndexs back to empty array at the end of you delete handler function.

const deleteDepartment = async () => {
   //your function code ....
   setRowIndexes([]);
   return;
}

Ravi Yadav
  • 316
  • 1
  • 7