1

I am relatively new to web development and javascript. Currently, I am trying to request a random dad joke from an API and make the joke appear on the page using the DOM. Whenever I try to make the joke append to my h2, it gives me promise object text.

Here is my HTML

<body>
    <div id="container">
        <h1>Dad Joke Generator!</h1>
        <button id="btn--joke">Click For a Dad Joke!</button>
        <button id="btn--reload">reload</button>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="app.js"></script>
</body>

Here is my JavaScript

//dad joke generator

//getDadJoke async function with axios
const getDadJoke = async () => {
  const headers = { headers: { Accept: "application/json" } };
  const res = await axios.get("https://icanhazdadjoke.com/", headers);
  return `here is the joke: ${res.data.joke}`;
};

//Selected HTML Elements (button and div(the div contains an h1 title and the button to create a joke))
const container = document.querySelector("#container");
const jokeButton = document.querySelector("#btn--joke");
const resetButton = document.querySelector("#btn--reload");

//createJoke function makes a new h2 (newJoke)
//tries to append the joke from the getDadJoke function to newJoke, and kinda works
//the newJoke is appended to the container div

const createJoke = () => {
  const newJoke = document.createElement("h2");
  newJoke.innerText = getDadJoke();
  container.append(newJoke);
};

jokeButton.addEventListener("click", () => {
  createJoke();
  console.log("This works!!");
});

resetButton.addEventListener("click", () => {
  location.reload(true);
});

Here is the result on a webpage

As you can see, my code works, but the joke from getDadJoke() doesn't append to the text of newJoke (h2)

If anyone could help me solve this issue, I would be eternally grateful, thanks!

Jayden Doll
  • 83
  • 1
  • 6
  • 1
    `getDadJoke()` is `async` so it returns a promise not the value returned in the function. To get that value you either need to use a `then()` callback, or use `async`/`await` for `createJoke` – Patrick Evans Sep 02 '21 at 08:34
  • 1
    I love the explanation you gave, that really helped! Thank you! – Jayden Doll Sep 02 '21 at 09:25

1 Answers1

0

To show the joke correctly, resolve the promise correctly by making the createJoke function asynchronous and await the async function getDadJoke.

const createJoke = async () => {
  const newJoke = document.createElement("h2");
  newJoke.innerText = await getDadJoke();
  container.append(newJoke);
};