Use useState hook to maintain persistent values across multiple function calls
<p>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). </p>
<p><strong>The problem is</strong>: 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. </p>
<p><em><strong>Example</strong></em>: 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']. </p>
<p>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</p>
<pre class="brush:php;toolbar:false;">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.... )</pre>
<p><br /></p>