Search code examples
javascriptreactjsdomcontentloaded

DOMContentLoaded doesn't work if i navigate to the page, only on refresh


So like i mentioned, the code inside DOMContentLoaded only runs when I refresh the page but if I navigate to said page the data in my table is no longer displayed. I have seen a very similar post here (DOMContentLoaded not firing after navigation but fires on page reload when using javascript_pack_tag) but i can't figure out the soution for my own code. This is what my code looks like:

import React from "react";
import "../Styles/Admin.css";
import fetch from "../axios";

const AdminDbCl = () => {
document.addEventListener("DOMContentLoaded", function () {
    fetch
      .get("http://localhost:9000/getClienti")
      .then((data) => loadHTMLTable(data["data"]));
  });

function loadHTMLTable(data) {
    const table = document.querySelector("table tbody");

    if (data.length === 0) {
      table.innerHTML =
        "<tr><td class='no-data' colspan='11'>No Data</td></tr>";
      return;
    }

    let tableHtml = "";

    try {
      for (var i in data) {
        data[i].map(
          ({ id_cl, nume_cl, prenume_cl, adresa_cl, nr_tel_cl, mail_cl }) => {
            tableHtml += "<tr>";
            tableHtml += `<td>${id_cl}</td>`;
            tableHtml += `<td>${nume_cl}</td>`;
            tableHtml += `<td>${prenume_cl}</td>`;
            tableHtml += `<td>${adresa_cl}</td>`;
            tableHtml += `<td>${nr_tel_cl}</td>`;
            tableHtml += `<td>${mail_cl}</td>`;
            tableHtml += `<td><button className="edit-row-btn" data-id=${id_cl}>Edit</td>`;
            tableHtml += `<td><button className="delete-row-btn" data-id=${id_cl}>Delete</td>`;
            tableHtml += "</tr>";
          }
        );
      }
    } catch (err) {
      console.log(err);
    }

    table.innerHTML = tableHtml;
  }


Solution

  • Previous answer is right as DOMContentLoaded event is fired once per page. When you navigate, it actually does not navigate to other page, instead you are on the same page, just the previous component is unmounting and new component is mounting. That's why it is single page application (SPA).

    Instead of using this event I would suggest you to use useEffect hook.

    React.useEffect(()=>{
     fetch
          .get("http://localhost:9000/getClienti")
          .then((data) => loadHTMLTable(data["data"]));
      });
    },[]) // empty array means this function has no dependency on any value and will be executed when the component is mounted on the dom.
    

    Or use componentDidMount method by making your component a class.

    componentDidMount(){
    fetch
          .get("http://localhost:9000/getClienti")
          .then((data) => loadHTMLTable(data["data"]));
      });
    }