-1

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.

3
  • 1
    (a) Please create a new minimal reproducible example which only shows the problem (responding to a deleted row) - and which does not show unrelated code. (b) Please ensure you have followed the integration guidelines for React with DataTables. (c) Please see an example of a runnable demo. You can base your MRE on that. Commented Feb 25 at 15:58
  • 1
    (d) Bear in mind that deleting a row from an HTML table (in the DOM) does not remove the row from the underlying DataTable. But since we cannot see the relevant code, it's difficult to know what your actual code is doing. (e) repeatedly needing to destroy() a DataTable should be avoided - and is not usually necessary. Commented Feb 25 at 15:58
  • Calling 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. Commented Feb 25 at 16:50

1 Answer 1

0

Try using callback function for updating state like this

const handleDelete = async (id) => { try { const endpoint = ui_data.pageType === "devices" ? '/devices?id=${id}' : '/users?id=${id}'; await deleteData(endpoint); setLocalRows(preRows => { return preRows.filter(row => row.id !== id); } ); } catch (error) { console.error("Error deleting:", error); } }; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.