Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect, useState } from "react";
- import DataTable from "datatables.net-react";
- import DT from "datatables.net-bs5";
- DataTable.use(DT);
- export default function Table() {
- const [users, setUsers] = useState(null);
- const columns = [
- { data: "name" },
- { data: "email" },
- { data: "created_at" },
- {
- data: null,
- render: function (data, type, row) {
- return `<button class="btn btn-sm btn-primary view-btn" data-id="${data.id}">View</button>`;
- },
- },
- ];
- const getAllUser = async () => {
- const res = await axios.get("/api/all-user");
- const users = res.data.users;
- setUsers(users);
- };
- useEffect(() => {
- getAllUser();
- }, []);
- useEffect(() => {
- const table = document.querySelector(".dataTable");
- let isListenerAttached = false; // Flag to track listener attachment
- const handleButtonClick = (e) => {
- if (e.target && e.target.classList.contains("view-btn")) {
- const id = e.target.getAttribute("data-id");
- console.log(`View button clicked for user ID: ${id}`);
- }
- };
- if (table && !isListenerAttached) {
- table.addEventListener("click", handleButtonClick);
- isListenerAttached = true; // Set the flag to true
- }
- return () => {
- if (table && isListenerAttached) {
- table.removeEventListener("click", handleButtonClick);
- isListenerAttached = false; // Reset the flag
- }
- };
- }, [users]); // Only runs when users change
- return users ? (
- <div className="table-responsive px-3">
- <DataTable
- data={users}
- columns={columns}
- className="display table table-hover user-table"
- options={{ pageLength: 25 }}
- >
- <thead className="table-primary">
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th>Created</th>
- <th>Action</th>
- </tr>
- </thead>
- </DataTable>
- </div>
- ) : (
- <div className="d-flex align-items-center p-5">
- <strong role="status">Loading...</strong>
- <div className="spinner-border ms-auto" aria-hidden="true"></div>
- </div>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement