Я пытаюсь асинхронно обновлять состояние, когда моя функция fetchWeather вызывается из моего WeatherProvider и делает запрос axios к API погоды.Результаты моего запроса отображаются на переменную прогноза внутри функции fetchWeather.
Я хочу установить новое состояние моего массива прогноза в качестве результатов прогноза из моей функции fetchWeather.Я пытался использовать setState различными способами, но мне все еще не удается обновить состояние.Что я тут не так делаю?
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>
)
}
}