Home > Net >  Problem with fetching body of a restful api?
Problem with fetching body of a restful api?

Time:12-14

I'm learning how to properly fetch an API in javascript into my code, and I am having some issues retrieving specific parts of the body. Ideally, I want to save the setup and punchline part of the body to be saved into a variable to be used later.

I wrote this:

fetch("https://dad-jokes.p.rapidapi.com/random/joke", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "dad-jokes.p.rapidapi.com",
        "x-rapidapi-key": "79142f2e8cmsh903cd5752a9ee77p1166f8jsnb9c812f77793"
    }
})
.then(res => res.json())
.then(data => console.log(data));

which returns this:

{
{
  success: true,
  body: [
    {
      _id: "60dd3699212bcedc7b8720a1",
      setup: "I saw a poster today for a free concert for those working in public health. It said 'Frontline Only'...",
      punchline: "Weird. I would've thought they'd fill the whole venue.",
      type: "health",
      likes: [],
      author: { name: "unknown", id: null },
      approved: true,
      date: 1618108661,
      NSFW: false
    }
  ]
}

As stated above, my desire here is to save the setup and punchline of the joke to a variable to be posted separately. How should I go about this? Thanks.

CodePudding user response:

You can define the variables for the data you wish to fetch before hand. As 'data.body' is an array, one element in length, we have to access it using data.body[0]. Then you can assign the variables using the names of the elements e.g 'body[0].setup'.

This should work! :-)

var setup;
var punchline;

var data = await fetch("https://dad-jokes.p.rapidapi.com/random/joke", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "dad-jokes.p.rapidapi.com",
        "x-rapidapi-key": "79142f2e8cmsh903cd5752a9ee77p1166f8jsnb9c812f77793"
    }
})

setup = data.body[0].setup; 
punchline = data.body[0].punchline; 
console.log(data); 
console.log(setup); 
console.log(punchline);

CodePudding user response:

I think the problem you're having is that fetch() is asynchronous. So, code that appears in the program on a line after the fetch statement will execute before your then() statement. A simple example:

runsFirst();
fetch.then(() => runsThird());
runsSecond();

So when you attempt to log these values outside your then() statement, you are actually logging them before they've been set. To actually get the values, you need:

var setup;
var punchline;

fetch("https://dad-jokes.p.rapidapi.com/random/joke", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "dad-jokes.p.rapidapi.com",
        "x-rapidapi-key": "79142f2e8cmsh903cd5752a9ee77p1166f8jsnb9c812f77793"
    }
})
.then(res => res.json())
.then(function (data){
    //Logs data
    setup = data.body[0].setup; 
    punchline = data.body[0].punchline; 
    console.log(setup, punchline); 
});

//Logs undefined
console.log(setup, punchline); 

If you find this syntax confusing, you can use async/await, and then lines will more or less execute in the order they are written, though the browser support is not quite as good.

  • Related