Search code examples
javascriptreactjssetstate

Asynchronously Updating State After A Function Call Returns API Results


I'm trying to asynchronously update the state when my fetchWeather function is called from my WeatherProvider and makes an axios request to a weather api. The results of my request are mapping to a forecast variable inside the fetchWeather function.

I want to set the new state of my forecast array to be the forecast results from my fetchWeather function. I've tried using setState in various ways but I still can't manage to update the state. What am I getting wrong here?

import React from 'react' 
import axios from 'axios'
import _ from 'lodash'

export const WeatherContext = React.createContext();

export class WeatherProvider extends React.Component {
constructor(props) {
    super(props)

    this.state = {
        context: {
            input: '',
            forecast: [],
            fetchWeather: WeatherProvider.fetchWeather
        }
    }

    this.fetchWeather = this.fetchWeather.bind(this)
}

fetchWeather = (term) => {
    let QUERY = term;
    const KEY = `key`
    let URL = `http://api.openweathermap.org/data/2.5/forecast?q=${QUERY}&appid=${KEY}`

    axios.get(URL)
    .then( res => {
        const forecast = _.flattenDeep(Array.from(res.data.list).map((cast) => [{
            date: cast.dt_txt, 
            temp_min: cast.main.temp_min,
            temp_max: cast.main.temp_max,
            group: cast.weather[0].main,
            detail: cast.weather[0].description,
            icon: cast.weather[0].icon
        }]) )

        this.setState(() => {
           forecast: forecast
        },() => { console.log(forecast, this.state.context.forecast) 
    })
}

render() {
    return (
        <WeatherContext.Provider value={{ ...this.state.context, fetchWeather: this.fetchWeather }} >
            { this.props.children }
        </WeatherContext.Provider>
    )
}
}

Solution

  • The state should be set like,

     .then( res => {
        ...
            let tempConetxt = {...this.state.context}
        tempContext.forecast = forecast;
            this.setState({context: tempContext},() => { console.log(forecast, this.state.context.forecast)
    

    Now value will updated in the context field of state.