0

I am trying to get data from the yelp api,

I have a fetching function that looks like this:

export function fetchRestaurants (term) {
    const endpoint = `businesses/search?term=${term}&location=NYC`

    return fetch(endpoint, {
      headers: new Headers({
        'Authorization': 'Bearer '+'oSJvaTmFtYVCEJcMsLFA4uRljDOILtEfp0sTWflSWclozapMP1rCZ6uttKPOoYnrdUGcTXI0ztOf3rTPVSBRa1JjngqcoTKD30YUp7yKxhZCNzS4bsZV_DqzzkAwXXYx',
      }), 
    })
      .then((res) => {
        console.log(res)
        res.json()
      })
      .then((data) => {
        console.log(data)
        // this is undefined!
        return data
      })
  }

the respose is 200 on the first then and looks like this:

Response {type: "basic", url: "http://localhost:3000/businesses/search?term=pizza&location=NYC", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:3000/businesses/search?term=pizza&location=NYC"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true

But then i try to do a .json on it on the second then, and when i try to log it its undefined.

Any ideas on how to get the actual data? Thanks

1 Answers1

2

The first .then callback function needs to return the res.json() Like this:

.then((res) => {
    console.log(res)
    return res.json()
  })
silencedogood
  • 3,209
  • 1
  • 11
  • 36
  • no because the second one which is called `data` in my example is undefined.. so i cant call .json on undefined. –  Feb 06 '20 at 15:09
  • 1
    @giorgiomartini — `data` is undefined in the second `then` **because** you didn't return anything from the first `then` (which this answer tells you to correct). – Quentin Feb 06 '20 at 15:09
  • 1
    That's because you didn't return anything in the previous callback in the promise chain... – silencedogood Feb 06 '20 at 15:10
  • @silencedogood if you edit your answer to say that i needed to return the value on the FIRST then ill accept it,, thx –  Feb 06 '20 at 15:12
  • @giorgiomartini — It has `res.json` in it. The first one has `res.json` in it. The second one doesn't. It **shows** that it is talking about the first `then` already. – Quentin Feb 06 '20 at 15:13