Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'response.json is not a function' in async/await function

Trying to turn my response into json. I'm not quite sure I'm getting TypeError: response.json is not a function error. Can someone please point me in the right direction. Thanks in advance.

    componentDidMount(){
        this.timingFunction = setInterval(() => this.getAllStations(), 1000);
    }


    async getAllStations(){
        try{
            const response = await(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
            const data = await response.json();
            console.log(`Here: ${data}`)


        }catch(e){
            console.log(`Error: ${e}`)
        }

    }

I expected to see the json response but got the error message. edit: Added await in front of response.json(); and got no where.

like image 707
Cam Avatar asked Jun 05 '19 05:06

Cam


People also ask

What is response JSON ()?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

Is response JSON a promise?

Because you receive the response as soon as all headers have arrived. Calling . json() gets you another promise for the body of the http response that is yet to be loaded.


1 Answers

You're missing the call to fetch (or whatever else you use to get data from the api). Right now it looks like you've mistaken await for a function.

const response = await(`http:api.bart.gov...

(You're also missing the two slashes after the http but that's not a problem yet.)

Try this:

const response = await fetch(`http://api.bart.gov...

like image 176
Eric Banisadr Avatar answered Oct 03 '22 17:10

Eric Banisadr