Another API related Question 🤦‍♂️

Hi, so I want to generate a page that has three random Chuck Norris jokes, I have used the code as per below, however I get the same joke on all three, is there a way to get three random ones and not the same ones and how would I write it to html?

JavaScript:

fetch("http://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(function(result) {
    jokes = result.value[1].joke;
    jokes2 = result.value[1].joke;
    jokes3 = result.value[1].joke;
    console.log(jokes + " " + jokes2 + " " + jokes3);
  }),
  error => {
    console.log(error + "");
  };

I created the below on my HTML page;

<div id="jokes" class="container mt-5">
        <p id="joke1">Joke 1</p>
        <p id="joke2">Joke 2</p>
        <p id="joke3">Joke 3</p>
    </div>

Hello!

Your code is almost right:

fetch("http://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(function(result) {
    // You're using the same result for every jokes* variable: result.value[1].
    // The fix:
    jokes = result.value[0].joke;
    jokes2 = result.value[1].joke;
    jokes3 = result.value[2].joke;
    console.log(jokes + " " + jokes2 + " " + jokes3);
  }),
  error => {
    console.log(error + "");
  };

The previous code should work.

Now I feel I can kick myself lol. I see what you are saying by calling the same joke three times, I didn’t call a different one, just the same line three times.

So now to add it to my HTML document and have it populate automatically, I just add this:

document.getElementByID('joke1').innerHTML = jokes;
1 Like

Worst things happens :stuck_out_tongue:.

Imagine having thousands of lines of code and, for some unexplained reason, the project doesn’t work. After hours You find that a semicolon was missing :sob:.

This happens to (almost?) everyone, that’s why there exists QA (Quality Assurance).

1 Like

You could also dynamically add the jokes with something like:
HTML

<div id="jokes" class="container mt-5"></div>

JavaScript

fetch("https://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(({ value: jokes }) => {
    document.getElementById("jokes").innerHTML = jokes
      .reduce((html, { joke }, idx) => (html += `<p id="joke${idx + 1}">${joke}</p>`), '');
  }),
  error => {
    console.log(error + "");
  };
1 Like

Or if you think the reduce method looks a bit messy, you can use the map method and join method.

fetch("https://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(({ value: jokes }) => {
    document.getElementById("jokes").innerHTML = jokes
      .map(({ joke }, idx) => `<p id="joke${idx + 1}">${joke}</p>`)
      .join('');
  }),
  error => {
    console.log(error + "");
  };
2 Likes

If I do this though I get the error as per below;
‘(node:1652) UnhandledPromiseRejectionWarning: ReferenceError: document is not defined’

I tried this way as well, but get the same error,

fetch("http://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(function(result) {
    jokes = result.value[0].joke;
    jokes2 = result.value[1].joke;
    jokes3 = result.value[2].joke;
    console.log(jokes + " " + jokes2 + " " + jokes3);
    document.getElementById("joke1").innerHTML = jokes;
    document.getElementById("joke2").innerHTML = jokes2;
    document.getElementById("joke3").innerHTML = jokes3;
  }),
  error => {
    console.log(error + "");
  };

How are you running this code? Through the browser?

No, still in VS Code and terminal. I am using live preview to view the html page in the browser though.

What does your html file look like?

Can I post the entire page here? Its a normal html file, with headings, body and script tags.

To enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Task 5</title>
</head>

<body>
    <div class="jumbotron jumbotron-fluid text-dark text-center" id="headingID">
        <div class="container">
            <h1 class="display-2" id="header">Some fun with Chuck</h1>
        </div>
    </div>
    <div id="jokes" class="container mt-5">
        <p id="joke1">Joke 1</p>
        <p id="joke2">Joke 2</p>
        <p id="joke3">Joke 3</p>
    </div>

    <!-- Optional JavaScript -->
    <script type='text/javascript' src="chuck.js"></script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous">
    </script>
</body>

</html>

Just for testing purposes, what does the chuck.js file look like?

Sure no problem sir, it looks like this:

require("isomorphic-fetch");

fetch("http://api.icndb.com/jokes/random/3")
  .then(res => res.json())
  .then(function(result) {
    jokes = result.value[0].joke;
    jokes2 = result.value[1].joke;
    jokes3 = result.value[2].joke;
    console.log(jokes + " " + jokes2 + " " + jokes3);
    document.getElementById("joke1").innerHTML = jokes;
    document.getElementById("joke2").innerHTML = jokes2;
    document.getElementById("joke3").innerHTML = jokes3;
  }),
  error => {
    console.log(error + "");
  };

Would it work by running the code in an IIFE function?

That is an npm module. You do not need that line. When I comment out that line, it works fine on my local machine.

image

1 Like

May I ask as to why though? I was under the imperession that it is required on the page for the fetch() function?

Only if you are running a back-end script via Node. If this is for front-end, fetch is a built-in feature of JavaScript.

Ah okay, so when this is server side I would use this right?