Hello, here's the problem: when I, through the API take data from the site using axios , connect this file to the component, write the result of the API request function to a new variable in state in the component, then pending Promise written there, and after a second promise it is updated and receives in [[PromiseValue]] an object with data, so how to write this object into a variable from state , and not an empty promise?

Code attached:

 var axios = require('axios'); export default function getWeatherData( town ) { const SITE_URL = "http://api.openweathermap.org/data/2.5/weather"; const PRIVATE_ID = "************"; let request = `${SITE_URL}?q=${town}&APPID=${PRIVATE_ID}`; return axios.get(request) .then(r => r.data); } 

As well as the component code:

 import React, { Component } from 'react'; import './App.css'; import getWeatherData from './api/getWeather'; class App extends Component { state = { weatherData: getWeatherData('Kiev') } componentDidMount() { console.log(this.state.weatherData) } render() { return ( <div> <h1>Hello world</h1> </div> ); } } 

Screen from console:

  • Not understood. Promise will always return a promise. If you need a value, then you need to transfer it somewhere in the .then block - Dmitry Kozlov

2 answers 2

If you do not use any wrappers and just React, then the logic for working with initial fetch is usually something like this:

  1. Initializing something with a state, say null.

     state = {weatherData: null} 
  2. In nothing we draw if there is no data (you can of course draw the initial frame if you want).

     render(){ if(this.state.weatherData === null){ return null; } } 
  3. In componentDidMount, we call our asynchronous operation to retrieve data, and when it completes, we change state accordingly;

     componentDidMount(){ this.getWeatherData().then(weatherData => this.setState({weatherData: weatherdata}) } 

This is the simplest approach to illustrate the principle. It is working, but in complex applications, usually a couple of levels of abstraction are heaped up, such as interaction with the storage and a number of small ui optimizations.

    If I understand correctly, do you want to get the value of r.data when mounting the component? But an asynchronous request does not have time to complete before the component is mounted. And you need to change the state of the component after receiving r.data

    Option 1. Put getWeatherData inside the App and setState inside the .then block

     .then((r) => { this.setState({ weatherData: r.data }) } 

    Option 2. Use any technique with a single repository of flux / redux, etc. and in the .then block call the dispatcher with the action of changing the city in the App