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();
}, [])
CodePudding user response:
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.
CodePudding user response:
if you want to update the dom you should cause a rerender in your app define a state and setState your new data