How to transfer a function as a requisite in a Response?

I have a GetWeather functional component that I want to pass the result of the GetLocation function to as a props, based on which GetWetaher will do something, that is, another request for receipt (in the example below, it displays only the props). I think this should happen inside ComponentDidMount, not sure how to do it.

    function GetLocation() {
        axios.get('http://ipinfo.io')
          .then((res) => {      
            return res.data.loc;
          })

      }
    function GetWeather(props) {
    //more code here, including another get request, based on props
        return <h1>Location: {props.location}</h1>;    
    }

    class LocalWeather extends Component {           
      componentDidMount() {    
        //???     
      }          
      render() {
        return (
          <div >                         
                <GetWeather location={GetLocation}/> //???                                               
          </div> 
        );
      }
    }

Update: So based on Damian's suggestion below works for me

function GetWeather(props) {   
    return <h3>Location: {props.location}</h3>;   
}

class LocalWeather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      location: []
    }; 
  }
  getLocation() {
    axios.get('http://ipinfo.io')
      .then((res) => {       
        this.setState({location:res.data.loc});        
      })         
  }

  componentDidMount() {    
    this.getLocation();     

  }
  render() {
    return (
      <div >                       
            <GetWeather location={this.state.location}/>                                                 
      </div> 
    );
  }
}
+4
source share
1 answer

you can also do it

constructor()
    {

        super();

        this.state=
        {
        Location:[]


        }

    }
     function GetLocation() {
        axios.get('http://ipinfo.io')
          .then((res) => { 
this.setState ({    
            Location:res.data.loc;
})
          })

      }
    function GetWeather(props) {

        return <h1>Location: {this.props.location}</h1>;    
    }

    class LocalWeather extends Component {           
      componentDidMount() {    
        //???     
      }          
      render() {
        return (
          <div >                         
                <GetWeather location={this.GetLocation.bind(this)}/>                                            
          </div> 
        );
      }
    }
+4
source

Source: https://habr.com/ru/post/1676062/


All Articles