Can't call fetch api multiple times

Shourya

I want to call this api multiple times in my project and when I am calling it , It continues giving an error which is

TypeError: Failed to execute 'json' on 'Response': body stream already read at main.js:Line number

My Code is as Follows

let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
    return data.json()
}).then((apidata) => {
    console.log(apidata)
    return apidata
}).catch((error) => {
    console.log(error)
})


a.then((fetchdata) => {
    return fetchdata.json()
}).then((readingData) => {
    console.log(readingData)
}).catch((err) => {
    console.log(err)
})
T.J. Crowder

You're not calling fetch multiple times. You're calling it once, and then trying to read the response body multiple times. That's why the error says you're trying to read the body when the stream is already closed — it was closed when you were done reading it the first time.

If you want to use the data twice, store it somewhere and use it twice.

let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
a.then((data) => {
    return data.json()
}).then((apidata) => {
    // **************** Use it twice here
}).catch((error) => {
    console.log(error)
})

If you want to fetch it again because it may have been updated, call fetch again:

let thisIsUrl = 'https://api.covid19api.com/summary';
fetch(thisIsUrl)
.then((data) => {
    return data.json();
}).then((apidata) => {
    console.log(apidata);
    return apidata;
}).catch((error) => {
    console.log(error);
});


// Presumably this is later (in time), not immediately after the above
fetch(thisIsUrl)
.then((fetchdata) => {
    return fetchdata.json();
}).then((readingData) => {
    console.log(readingData);
}).catch((err) => {
    console.log(err);
});

Finally, this seems unlikely, but if you really want to fetch it once and use that one result in multiple places via the promise chain, keep the promise from then rather than the promise from fetch:

let thisIsUrl = 'https://api.covid19api.com/summary';
let a = fetch(thisIsUrl)
.then((data) => {
    return data.json()
});
a.then((apidata) => {
    // ***** Use it here
}).catch((error) => {
    console.log(error)
})

a.then((readingData) => {
    // ***** And then again here
}).catch((err) => {
    console.log(err);
});

Side note: Your code is falling prey to a footgun in the fetch API; I've written about it in this blog post. fetch only rejects its promise on network errors, not HTTP errors. You have to check for those yourself in the first fulfillment handler, by checking for ok on the response object:

fetch("/your/resource")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status); // Or better, use an Error subclass
    }
    return response.json();
})
// ...

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

fetch API call being sent multiple times

Can't call function of class multiple times

Error: Can't call startAt() or equalTo() multiple times

Call an API multiple times with a different URL in Python

React - API call running multiple times

Can't fetch API Resource

Metadata call multiple times in breeze can it reduce?

Call Action<T> multiple times with collection as input

Parse iOS : Can't modify UI Elements when i save a file and call a function multiple times

React Fetch API Being Called Multiple Times on page load

Can I fetch() multiple times in a loader function and extract it with one useloaderdata()?

Cannot fetch data from an API using componentDidMount: Can't call setState (or forceUpdate) on an unmounted component

Can't call API to fetch cpu data from preload.js | Electron, cpu-utils

API call can't fetch ONLY the value on the backend (nodejs) from front-end (react)

Can't request from website multiple times

Can't iterate the "filter" filter multiple times

Flutter: Can't fetch json API data

Can't fetch API from React application

fetch data multiple times in one fetch

Fetch multiple posts from JSON Placeholder with one API call

How to fetch multiple data from api call and bind to a flutter widget

Looping API call multiple times getting random results

PHP | Call an API multiple times as a different link and get the data

How to call Api multiple times with different parameters and then store the responses?

C#-how to use the result of an API call multiple times

How can I make a multiple Fetch Call in Ui5?

Spring AOP: In an Around advice, can I call proceed() multiple times?

How can I call Speech Recognition multiple times in 1 function?

How can I correctly make the fetch api call in react?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive