-1

I am trying to write a useEffect hook which will update the DOM once when the page loads. For some reason that I cannot fathom, the useEffect runs but the function does not get called. The console.log() on the other hand does get called.

There is no problem with the function itself, it works when I run it from the console or trigger it in some other way. I have also tried using different syntax for writing and/or calling the function, placing inside or outside the useEffect. The result is always the same—the DOM does not update but the console.log() logs.

Please help me, what am I doing wrong/ misunderstanding? Thank you in advance.

  // Add ids to h2 elements inside markdown
  useEffect(() => {
    function setID() {
      const H2List = document.getElementsByTagName("h2");
      const H2Array = [...H2List];
      H2Array.map((a) => (
        a.setAttribute('id',
        `${H2Array[H2Array.indexOf(a)].childNodes[0].nodeValue
          .split(" ").join("-").toLowerCase()}`)
      ))
    }
    console.log("useeffect ran once");
    setID();
  }, [])
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Freja
  • 49
  • 1
  • 7

2 Answers2

0

After some more Googling, this works:

  window.onload = function() {
    setID()
  }

  function setID() {
    const H2List = document.getElementsByTagName("h2");
    const H2Array = [...H2List];
    H2Array.map((a) => (
      a.setAttribute('id',
      `${H2Array[H2Array.indexOf(a)].childNodes[0].nodeValue
        .split(" ").join("-").toLowerCase()}`)
    ))
  }

Thank you to this source.

Freja
  • 49
  • 1
  • 7
-1

if you want to update the dom you should cause a rerender in your app define a state and setState your new data

  • Hi @mohammad gharouni thanks for replying. I was under the impression that with an empty dependancy array, a useeffect would run once with initial render, is this not the case? I'm happy to try usestate and report back. – Freja Nov 18 '22 at 11:42