I am calling the "deleteDepartment" function on a button to delete the department row in the table. Get the selected row index from the table (I'm using shancn table using tanstack table) in "selectedRows" hook (pass setSelectedRows as prop to the table component which gets the value from the rowSelection hook in the table).
The problem is: I am able to delete the first two or three rows without any problems, but when I continue deleting, the "rowSelection" state saves the value from the previous function call and changes It is added to the currently selected rows array.
Example: If I delete row['1'] and next time I click button to delete row 2, then the value of 'rowSelection' should Just ['2'], but it's added to the previous value like ['1', '2'].
I'm lost on why this behavior occurs. I thought this might be due to closures and async nature, so I used the useCallback hook, but it didn't work. Please help someone with better knowledge
const DepartmentsAndRolesPage = () => { const [departments, setDepartments] = useState([]); const [selectedRows, setSelectedRows] = useState({}); const [rowIndexes, setRowIndexes] = useState ([]); 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.... )
At the end of your delete handler function, you should set
rowIndexes
to an empty array.