0

I have a REACT component:

import React from 'react';
import Weather from '../service/weatherAPI.js';

export default class DisplayWeather extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      weatherData: []
    }

    this.getWeatherData = this.getWeatherData.bind(this);
  }

  componentDidMount(){
    this.getWeatherData();
  }

  async getWeatherData(){
    let data = await Weather(this.props.location)
    this.setState({ weatherData: data});
    console.log(this.state.weatherData)
  }

This function references a function exported from another file which is using fetch to call an endpoint. All the data returns correctly from the endpoint I am calling. However, when trying to set this data onto the state, my data is undefined.

Below is my API call, just in case I have missed anything here:

const Weather = (location) => {
      fetch(url, {
        Method: 'GET',
        headers : {
            'Accept': 'application/json'
          },
      })
      .then((raw) => raw.json())
      .then((response) => {
        return response
      })
    }

export default Weather; 

Thanks in advance.

7
  • You have to use promises for yuor fetch function Commented Jan 13, 2020 at 19:11
  • Did the request go through when you check the network logs? Commented Jan 13, 2020 at 19:12
  • You need to transform response and assing it to your state Commented Jan 13, 2020 at 19:12
  • can you show full code example? Commented Jan 13, 2020 at 19:22
  • @wentjun Yes I got the response I expected. Commented Jan 13, 2020 at 19:23

1 Answer 1

1

You need to return the promise like this in your weather function:

const Weather = (location) => {
  return fetch(url, {
    Method: 'GET',
    headers : {
        'Accept': 'application/json'
      },
  })
  .then((raw) => raw.json())
  .then((response) => {
    return response
  })
}

That way the await is working on the promise instead of just the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.