how to reinitialize table in react inside a useEffect when a dependency has changed ?

how to reinitialize table in react inside a useEffect when a dependency has changed ?

nijinenijine Posts: 6Questions: 1Answers: 0
edited October 2023 in Free community support

The code

import React, { useEffect, useRef, useState } from "react";
import DataTable from "datatables.net-bs5";
import "datatables.net-colreorder-bs5";
import "datatables.net-fixedcolumns-bs5";
import "datatables.net-bs5/css/dataTables.bootstrap5.min.css";
import { useQuery } from "@tanstack/react-query";
import { getTableData } from "../util/commonHelper";
import { useSyncDispatch, useSyncState } from "../context/SyncContextProvider";

export default function Table({ config }) {
  const [params, setParams] = useState({});
  const tableRef = useRef(null);
  const tableInstance = useRef(null);

  // useQuery to fetch data from the api
  const { data, isLoading, isSuccess } = useQuery({
    queryKey: ["tableData", params],
    queryFn: getTableData,
  });

  // This useEffect will try to initiate the datatable instance
  // at componentDidMount and componentDidUpdate (see the dependency array in useEffect)

  //  At componentDidMount everything works fine but whenever I try to change the
  // Entries of the table (see the handleChangeEntries function) to update the entries per page
  // via another api call with updated params the  the react or the table itself throw some error I will attach it in bleow of this code,

  useEffect(() => {
    tableInstance.current = new DataTable(tableRef.current, {
      dom: "rtip",
      paging: false,
      bInfo: false,
      fixedColumns: {
        left: 0,
      },
      colReorder: {
        enable: false,
        // order: syncState[config.table].order,
      },
      // initComplete: function () {
      // },
    });

    // Clean up the table instance when the component unmounts
    return function () {
      tableInstance.current.destroy();
    };
  }, [data]);

  // This handleChangeEntries function set the required params to the state and the useQuery
  // make another request with the params and try to reInitialize the table with new data and endup with some error
  const handleChangeEntries = (event) => {
    console.log(event.target.value);
    console.log("handleChangeEntries");
    setParams((prev) => ({
      ...prev,
      perPage: event.target.value,
    }));
  };

  if (isLoading) {
    return (
      <div>
        <p>Loading ...</p>
      </div>
    );
  }

  if (isSuccess) {
    return (
    jsx for rendering the table goes here if it needed plz ask me to post
    );
  } else {
    return (
      <div>
        <p>Loading...!</p>
      </div>
    );
  }
}

this is the queryFunction that used in useQuery

export const getTableData = async ({ queryKey }) => {
  // console.log(queryKey);
  try {
    const response = await axios.get('api/transactions',{
      params:{
        ...queryKey[1]
      }
    });
    // const response = await axios.get('api/transactions');

    if (response.status !== 200) {
      throw new Error(`Request failed with status code ${response.status}`);
    }

    return response.data.responseData;
  } catch (error) {
    console.error(error);
    throw error; // Re-throw the error to be caught by the caller
  }
};

Error message from console

4 Table.jsx:64:12
handleChangeEntries Table.jsx:65:12
Object { current: {…} }
Table.jsx:18:10
Uncaught DOMException: Node.removeChild: The node to be removed is not a child of this node
    React 73
react-dom.development.js:11099:2
    React 73
    receiveMessage SelectChild.sys.mjs:265
    receiveMessage SelectChild.sys.mjs:467
Uncaught DOMException: Node.insertBefore: Child to insert before is not a child of this node
    jQuery 4
    Table Table.jsx:57
    React 19
jquery.dataTables.mjs:9632:3

The above error occurred in the

<

table> component:

table
div
Table@http://127.0.0.1:5173/resources/js/components/Table.jsx?t=1698371457791:26:30
div
section
section
TransactionContent@http://127.0.0.1:5173/resources/js/pages/transaction/TransactionContent.jsx:24:24
section
main
Card@http://127.0.0.1:5173/resources/js/components/Card.jsx:19:29
Transaction
RenderedRoute@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:3408:7
Outlet@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:3728:20
MainLayout@http://127.0.0.1:5173/resources/js/layouts/MainLayout.jsx:23:20
RenderedRoute@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:3408:7
Routes@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:3790:7
Router@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:3741:7
BrowserRouter@http://127.0.0.1:5173/node_modules/.vite/deps/react-router-dom.js?v=9e5db6ba:4387:7
TablePannelContextProvider@http://127.0.0.1:5173/resources/js/context/SyncContextProvider.jsx:34:51
QueryClientProvider@http://127.0.0.1:5173/node_modules/.vite/deps/@tanstack_react-query.js?v=9e5db6ba:2586:27
Router

I just detailed everything about the problem inside the code I provided with commands for ease of understanding! is any further info need plz ask me I almost spend 2 days to understand what is going on in the table ,one thing I assume that , the jquery changes the DOM directly .Thanks in advance

Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

Replies

  • nijinenijine Posts: 6Questions: 1Answers: 0

    Sorry for the inconvenience may be I didn't format the content correctly I new to this forum I will learn it

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951
    edited October 2023

    To highlight code, use triple back ticks (```) on new lines before and after the code block. See the Markdown docs for more info.

    Hopefully @allan can help with the React troubleshooting.

    Kevin

  • nijinenijine Posts: 6Questions: 1Answers: 0

    Thank you @kthorngren

  • nijinenijine Posts: 6Questions: 1Answers: 0

    @allan could you please help on this issue !

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    I'm really sorry - I currently know very little about React. It is high on my list of things to learn and implement as a plug-in for DataTables, but at the moment, I have no clue how to resolve this. Sorry.

    Allan

  • nijinenijine Posts: 6Questions: 1Answers: 0

    Thank you allan. I'll try my best on this

  • ayzayz Posts: 63Questions: 23Answers: 1
    edited December 2023

    Has this been resolved? In handleChangesEntries, should you not trigger a jquery re-render of the table as the entries change? What happens if “params” is made part of the dependency array? Could you also include the table jsx?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    A React integration for DataTables is high on my agenda for after DataTables 2 is available. I've not been able to make progress on it due to the time spent on DT2. It should drop early in the new year.

    Allan

  • ayzayz Posts: 63Questions: 23Answers: 1

    Where can I read up what DT2 brings?

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    There'll be release notes and a blog post in the new year when it's released - if you keep an eye on the forum there'll be announcements here.

    Colin

Sign In or Register to comment.