0

I read this answer on returning data from async requests, but I am still having difficulty determining how to apply these answers in my application.

In the code below, I am trying to access the returned result of the getWeather async request and use that data in the jsx that follows in the return statement below getWeather.

I noticed the answers to the previous OP's question said to handle the results in a callback function, but I don't know how to get that passed back up the chain as a result of the getWeather call.

My question - how can I pass this data back and access it inside of the FiveDayWeather function?

const URL = `http://api.openweathermap.org/data/2.5/forecast?zip=94040&appid=${OPEN_WEATHER_KEY}`

const FiveDayWeather = () => {
  let days = getWeather()

  return(
    <div className="five-day-weather">
      <div className="day-of-week-item">
        <div className="day">Hi Again</div>
        <div className="image-indicator"></div>
        <div className="temp"></div>
      </div>
    </div>
  )
}

function getWeather() {
  axios.get(URL)
    .then(function(response) {
      handleData(response)
    })
}

function handleData(response) {
  return response
}
Joshua
  • 3,055
  • 3
  • 22
  • 37
adamscott
  • 823
  • 1
  • 10
  • 31

2 Answers2

2

You should be making the API call in componentDidMount method and set the result in the state of the component. Then in your render method, you need to use state.

constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      days: []
    };

  }

getWeather() {
  axios.get(URL)
    .then(response => {
       this.setState({
           isLoaded: true,
           days: response //Set the right value here from response
       });
    }).catch( error => {
       this.setState({
           isLoaded: true,
           error
       }); 
    });
 }

render() {
    const { error, isLoaded, days } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        // your template to show the data goes here
      );
    }
  }

Refer to the ReactJS docs for AJAX here.

GSSwain
  • 5,787
  • 2
  • 19
  • 24
0

Your function getWeather() isn't returning something, and the handleData() is not doing what you think.

Instead of lots of returns, you should try a async function. The axios works asynchronously. So, the await will wait until the data is retrieved from axios, an then return it. Try like this:

async function getWeather() {
 return await axios.get(URL)
}
reisdev
  • 3,215
  • 2
  • 17
  • 38