A guide on harnessing the power of the fetch API to retrieve data from an external

In the process of developing a fetchBill function, I have assigned the URL https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3 to a variable named api. This function utilizes the browser's fetch function to send an HTTP request to the specified API. Within a .then method attached to the fetch call, an arrow function is used to handle the response, converting it into JSON format before returning it. Subsequently, another .then method is utilized to pass this JSON data to the displayCartTotal function. To ensure error handling, any potential errors are caught and displayed through a warning message in the console.

As outlined by the challenge requirements, the displayCartTotal function has been defined and verified for accuracy. Similarly, the fetchBill function has also been established, functioning as intended with its returned promise having a status of "resolved" and containing an Array as the promiseValue. Despite no reported errors, this implementation appears not to address the underlying problem presented in the challenge yet.

    const displayCartTotal = ({results}) => results;

    const fetchBill = () => {
    const api = 
    "https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3";
    const results = fetch(api)
        .then(res => res.json())
        .then(data => displayCartTotal(data))
        .catch(err => console.log(`Warning!!! Error fetching data!!! 
        Error ${err}`));
        return results;
};

Upon invoking the displayCartTotal function within the fetchBill function, the expected outcome is for it to return the 'results' property from the JSON object obtained via the fetch request. It is crucial to emphasize that the goal is to retrieve and return the promiseValue rather than the entire promise stemming from the HTTP request.

Answer №1

One potential cause for the process to fail could be due to the Javascript code continuing before the promise is fulfilled, causing the result variable to be returned prematurely.

A straightforward solution to this issue would be to place the return statement within a then block:

const displayCartTotal = ({results}) => results;

const fetchBill = () => {
const api = 
"https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3c";
const results = fetch(api)
    .then(res => res.json())
    .then(data => displayCartTotal(data))
   .then(return results;)
    .catch(err => console.log(`Warning!!! Error fetching data!!! 
    Error ${err}`));
};

Answer №2

Your specific situation involves a fetch operation that returns a promise which remains unfilled. You need to modify the fetch method accordingly.

fetch('https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3c')
    .then((resp) => {
        if (!resp.ok) {
            if (resp.status >= 400 && resp.status < 500) {
                return resp.json().then((data) => {
                    let err = { errorMessage: data.message };
                    throw err;
                });
            } else {
                let err = { errorMessage: 'Please try again in some time, Server Error!' };
                throw err;
            }
        }
        return resp.json();
    })
    .then((data) => {
        console.log(data.results[0].buyerCountry);
        console.log(data.results[0].itemsInCart);
    })

Answer №3

function calculateTotalPrices({items}) {
  return items;
}

function fetchFinalBill() {
  const apiEndpoint = "https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3c";
  
  fetch(apiEndpoint)
    .then(response => response.json())
    .then(data => calculateTotalPrices(data))
    .catch(err => console.error(err));
}

Answer №4

  ConstructTokenFromJson(Map<String, dynamic> jsonData) {
    accessKey = jsonData['access_token'];
    typeOfToken = jsonData['token_type'];
    refreshIdToken= jsonData['refresh_token'];
    expirationTime= jsonData['expires_in'];
    scopeInfo= jsonData['scope'];
  }

  Map<String, dynamic> convertToJson() {
    final Map<String, dynamic> dataMap = new Map<String, dynamic>();
    dataMap['access_token'] = this.accessKey;
    dataMap['token_type'] = this.typeOfToken;
    dataMap['refresh_token'] = this.refreshIdToken;
    dataMap['expires_in'] = this.expirationTime;
    dataMap['scope'] = this.scopeInfo;
    return dataMap;
  }



 @override
  void startState() {
    ResourceService().fetchCountryDetails().then((responseObj) {
      setState(() {
        countriesList = responseObj;
        isLoadingData = false;
      });
    });
    super.initState();
  }

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

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Use vtip jQuery for showcasing titles

Currently, I am utilizing the vTip plugin for displaying titles upon hover. Here is a snippet of my code: http://jsfiddle.net/bnjSs/ In my HTML, there's a Div with the ID #showTitles. Whenever this Div is clicked, I aim to toggle the display of all ...

What is the best way to modify this state without altering the original array?

I am seeking guidance on how to avoid mutating state in a specific scenario: In my React Hooks setup, I have a TodoList component that displays a list of TodoItems. Each TodoItem can be clicked to trigger a function called toggle, which switches its compl ...

How can I extract a substring from a URL and then save it to the clipboard?

Hi there! I'm working on a project for my school and could really use your expertise. I need help extracting a substring from a URL, like this one: URL = https://www.example.com/blah/blah&code=12432 The substring is: 12432 I also want to display ...

Working with JSON data retrieved from a PHP and MySQL backend in an AngularJS application

Having difficulty handling the JSON response from PHP. I am using AngularJs to display the received JSON data. As a newcomer to Angular, I attempted a basic exercise and would appreciate some assistance. Thank you in advance. index.html <!DOCTYPE HTML ...

What is the best way to adjust the border radius of a TextField component in Material-UI React?

I've been attempting to customize the border radius of a TextField in MUI without any success. The current borderRadius is set to 4px, and I'm trying to change it to 0px. Here is the code I've been using: <TextField id="time&q ...

Response triggering redirection of jQuery

I'm attempting to showcase images for each result that I receive. Below is the code I am currently using: $(document).ready(function() { var frm = $('#searchmovie'); frm.submit(function (ev) { $.ajax ...

Transferring a Data array from JSON to a WCF function as a parameter

Hello everyone, I am utilizing JSON to transfer data in a WCF service. Below is the code snippet that shows how I am successfully passing data using ProjectCollection. However, my goal is to pass data as an array like this: var ProjectCollection = [&apos ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Discovering the `findIndex` malfunction in Internet Explorer

Having just finished a small form, I realized that my current implementation of findIndex is not compatible with IE. Let's take a look at an example of the problem: var people = [ {name:"Mike", age:"25"}, {name:"Bill", age:"35"}, {name:"Terry" ...

The option list in AngularJS is cleared when an option is selected

In my current project, I am developing a django-tastypie api application with angularjs as the JavaScript framework. The main part of this application involves managing curriculum objects, each containing a list of grade objects and each grade object furth ...

detect faces in an image using Microsoft's cognitive services by uploading an image from your device

As a newcomer to Face Recognition technology, I have been searching for answers to my questions without much success. I have learned that uploading an image from the web requires using Content-Type application/json and providing the image URL in the JSON ...

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

How to Use React JS to Obtain the Full File Path

I am currently using an Input type 'file' to browse files on my machine through a react js application. After selecting the file from my local directory, I would like to obtain the absolute path of the file - for example: C://something/something. ...

Certain mobile devices experiencing issues with AngularJS filters

Currently, I am attempting to filter an AngularJS array by utilizing custom filters within a controller. The filters are functioning correctly on certain mobile devices, yet they are not working on others. Here is the code snippet that I am using: var a ...

What is the process of uploading files using Ajax?

Can anyone help me with submitting a form using ajax that contains images? I have this code snippet which logs an object called "FormData" in the console, but I'm not sure how to properly use it or retrieve it. Is this the correct approach? $("#form_ ...

Issue with Web API and AJAX: Unable to retrieve resource, server returned status code 400

[HttpPost("Login")] public async Task<IActionResult> Login([FromBody] SigninViewModel formData) { MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(f ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Sending an array from Ajax to PHP

I am new to working with AJAX. I have created an array using a JavaScript function from a button table, but I have been unsuccessful in passing it to my PHP file. Even after trying methods like print_r, var_dump, nothing is being printed in my *.php file. ...