I am using DataTables in a NextJS project.
I'm getting data from the backend with:
const [rows, setLocalRows] = useState([]); useEffect(() => { if (Array.isArray(initialRows)) { setLocalRows(initialRows); } else { setLocalRows([]); } }, [initialRows]); and I update my table with every row changes like:
useEffect(() => { const table = $(tableRef.current); if ($.fn.dataTable.isDataTable(table)) { table.DataTable().clear().destroy(); } if (rows.length > 0) { console.log(rows); table.DataTable({ pageLength: 10, language: { search: '' } }); } return () => { if ($.fn.dataTable.isDataTable(tableRef.current)) { table.DataTable().destroy(); } }; }, [rows]); but when I try to delete a row from the table, it doesn't get deleted instantly.
const handleDelete = async (id) => { try { const endpoint = ui_data.pageType === "devices" ? '/devices?id=${id}' : '/users?id=${id}'; await deleteData(endpoint); const newRows = rows.filter(row => row.id !== id); setLocalRows(newRows); } catch (error) { console.error("Error deleting:", error); } }; How can I instantly refresh my table after triggering the handleDelete function?
I think DataTable is unable to detect React state updates but I couldn't find the solution.
destroy()a DataTable should be avoided - and is not usually necessary.setLocalRows(newRows);is sufficient enough to trigger a component rerender. What exactly is the issue or problem you have? Please edit to clarify and provide better details.