PanczerTank
PanczerTank

Reputation: 1130

Problem using JS ES6 promises in React - TypeError: Cannot read property 'then' of undefined

I import the function getWeather from another .js file I've written. The result is a json blob. I've verified that I get the JSON blob back, but when I try to call the getWeather function and use .then to wait for a response and set my state I get a TypeError.

getWeather(parseFloat(lat),parseFloat(long)).then((data) =>{
  this.setState({weatherType: data.currently.icon, temp: data.currently.temperature})
  return data
}).catch((error) => {
  console.log(error.message);
})

The getWeather function is here:

export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          return data.json();
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.log(error);
        });
    }

Upvotes: 0

Views: 463

Answers (2)

D Lowther
D Lowther

Reputation: 1619

You need to return fetch() in order to make the promise accessible from another function. Also, I would probably handle logging and errors in the calling function as when you log the data you are no longer returning it.

export function getWeather(lat,long) {
  const params = {
    headers: {
      "content-type": "application/json; charset=UTF-8",
      "Access-Control-Allow-Origin": "*"
    },
    method: "GET"
      };
      return fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          if (!data.ok) { return new Error('custom error message here') }
          return data.json();
        });
    }

Upvotes: 2

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

You are most probably return that blob from the getWeather function without creating a Promise. Try something like this:

function getWeather() {
// create blob as usual
  return Promise.resolve(blob);
}

or if you already inside a then you must just retrun something from it:

      fetch(`https://api.com/mykey/${lat},${long}`, params)
        .then(function (data) {
          return data.json();
        })
        .then(res => {
          console.log(res);

          retrun res; // return something 

        })
        .catch(error => {
          console.log(error);
        });
    }

Upvotes: 0

Related Questions