I have a list of records that fills a table and adds a remove button next to each record. When I press the remove button, in the console I can see that the records really did decrease by 1 and the item I selected to be removed is actually removed, but that change won't show on the page in the table itself. What could be the problem?
As you can see in the image below, when I click the remove button, the number or records decreases but the item wont be removed from the table itself.
const AddingTable = () => {
const [records, setRecords] = useState(someRecordsReturnedFromAnAPI);
let filterFn = { fn: items => { return items; } };
let headCells = [...];
const { TblContainer, TblHead, TblPagination, recordsAfterPagingAndSorting } = useTable(records, headCells, filterFn);
function handleRemoveClick(itemList, item) {
const index = itemList.indexOf(item);
itemList.splice(index, 1);
setRecords(itemList);
}
function TableRowWithRemove(props) {
let { itemList, item } = props;
return (
<TableRow>
//... Table cells with records contents
<TableCell>
<button onClick={() => handleRemoveClick(itemList, item)}> Remove </button>
</TableCell>
</TableRow>
)
}
return (
<>
<TblContainer>
<TblHead />
<TableBody>
{
recordsAfterPagingAndSorting().map((item, index) => (
<ConditionalTableRow key={index} item={item} itemList={records} />
))}
</TableBody>
</TblContainer>
<TblPagination />
<ConditionalDiv />
</>
);
}
const TblPagination = () => (
typeof records === 'undefined'?
[]
:
<TablePagination
component="div"
page={page}
rowsPerPageOptions={pages}
rowsPerPage={rowsPerPage}
count={records.length}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}/>
)
const recordsAfterPagingAndSorting = () => {
if (typeof records !== 'undefined') {
return stableSort(filterFn.fn(records), getComparator(order, orderBy))
.slice(page * rowsPerPage, (page 1) * rowsPerPage)
}
else
return null;
}
if (typeof recordsAfterPagingAndSorting !== 'undefined')
return {
TblContainer,
TblHead,
TblPagination,
recordsAfterPagingAndSorting
}
else
return {
TblContainer,
TblHead,
TblPagination
}
}
CodePudding user response:
try using, since splice
doesn't change the address of object.
function handleRemoveClick(itemList, item) {
const index = itemList.indexOf(item);
let newItemList =[...itemList];
newItemList.splice(index, 1);
setRecords(newItemList);
}