when I run this code I get an error saying I cannot set innerText of Null; I know this is because my function runs before my DOM fully loads in, but I do not know how to fix it.
I have tried using window.onload, and event listeners for loading, but to no avail.
Any help is appreciated, thanks !
import "./styles.css";
const quoteBox = document.getElementById("App");
async function newQuote() {
const response = await
fetch("https://api.quotable.io/random");
const data = await response.json();
quoteBox.innerText = data.content;
}
window.onload = newQuote();
export default function App() {
return <div className="App" id="App"></div>;
}
You can use useEffect so that function gets called after it is mounted.
export default function App() {
useEffect(() => {
const quoteBox = document.getElementById("App");
async function newQuote() {
const response = await
fetch("https://api.quotable.io/random");
const data = await response.json();
quoteBox.innerText = data.content;
}
newQuote();
}, []);
return <div className="App" id="App"></div>;
}
Either add your script tag at the end of your body tag or wrap everything in a function and call it on DOMContentLoaded