Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use.

Here is the code I have written:

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));

This code snippet returns the following response:

{
{
  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
    }
  ]
}

My objective is to extract and save the setup and punchline of the joke from the response for individual use. What would be the best approach to achieve this? Thank you.

Answer №1

Prior to fetching the data, it's important to define the variables you'll be using. Since 'data.body' is an array with a single element, you must access it via data.body[0]. After that, you can assign the variables using the element names, such as 'body[0].setup'.

This approach should do the trick! :-)

let setup;
let punchline;

const 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);

Answer №2

It seems like the issue you're experiencing is due to the asynchronous nature of fetch(). This means that code following the fetch statement will run before the then() statement. Here's a simple example to illustrate:

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

Therefore, when you try to log these values outside the then() statement, you're actually logging them before they've been set. To properly retrieve the values, you should do the following:

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 explore async/await as an alternative. This allows for more sequential execution of code, although browser support may vary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

What steps can be taken to prevent the browser from freezing when loading JSON via an ajax request?

Hello, I'm currently facing an issue where the dropdown and browser become locked until the ajax request is completed. I've learned that setting ASYNC to False for JSON Ajax requests should prevent this issue. Can someone please assist me in adju ...

What could be causing my list of files to not properly append to FormData?

I have been working on this issue for the past three days. Despite trying various solutions from different sources, including seeking help from other websites, I am still unable to resolve it. My current challenge involves sending a post request with a Fo ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

Tips for causing Jackson to throw an exception directly when deserialization mapping fails

Jackson exhibits an unusual behavior when handling Exceptions during deserialization mapping: it throws a JsonMappingException and the .getCause() method returns the innermost exception in the chain. //in main ObjectMapper jsonMapper = new ObjectMapper(); ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Utilizing jQuery Autocomplete to access JSON data via an API

My understanding of jQuery autocomplete is a bit limited, so I'm hoping for some guidance on how to achieve my task. I currently have the following URL: http://localhost/contactApi.do?mobile=614321 This URL allows for inputting either a complete or ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

What causes an ajax request to submit "none" as the value of a dom element?

Seeking assistance! I've encountered a frustrating issue with my simple input box in a form. I am attempting to send the value from this input box to Django using Ajax post, but keep encountering a 500 error that reads ValueError at /rest/ Cannot use ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

How come the values keep appearing without any loops or subsequent calls being made to the PHP file?

Here is a demo example showcasing 'Server Sent Events(SSE)': Embed HTML code(index.html) : <!DOCTYPE html> <html> <body> <h1>Receiving server updates</h1> <div id="result"></div> <script> if(type ...

The sequence of divs in a language that reads from right to left

Is there a way in HTML to designate a set of divs so that they automatically align from left to right for languages that read left to right, and alternatively, flow from right to left for languages that read right to left? This means that the direction of ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Adjusting Image Width with jQuery on Hover

I am trying to create a hover effect for two images placed side by side. When the user hovers over one of the images, it should expand. HTML: <a href="#"><div id="skinny"></div></a> <a href="#"><div id="room9"></div ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Transforming a React Class Component into a React Functional Component

After struggling for a day with multiple failed attempts, I have been unsuccessful in converting a React Class Component. The original class component code is as follows: class NeonCursor extends React.Component { constructor(props) { super(props); ...