React + Axios help parse

Please help me parse JSON through react and axios. There is such a code

class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        countryName: ''
        countryCode: ''
      }
    }

    componentDidMount() {
      axios.get('https://ipapi.co/json/').then((response) => {
        let data = response.data;
        this.setState({
          countryName: data.country_name,
          countryCode: data.country_calling_code
        });
      }).catch((error) => {
        console.log(error);
      });
    }

    render() {
      return ( <
        div >
        <
        p > Country Name: {
          this.state.countryName
        } < /p> <
        p > Country Code: {
          this.state.countryCode
        } < /p> <
        /div>
      )
    }

    ReactDOM.render( <
      App / > ,
      document.getElementById('root')
    );
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Demo</title>
  <script src="src/index.js"></script>
</head>

<body>

  <div id="root"></div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.1/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/0.14.1/react-dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>

</body>

</html>

And I can't fix the error

Author: Hudoi, 2019-06-18

3 answers

Everything works perfectly simple take a closer look at your code

Here is also a worker Codesandbox

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      countryName: "",
      countryCode: ""
    };
  }

  componentDidMount() {
    axios
      .get("https://ipapi.co/json/")
      .then(response => {
        let data = response.data;
        this.setState({
          countryName: data.country_name,
          countryCode: data.country_calling_code
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <p> Country Name: {this.state.countryName} </p>
        <p> Country Code: {this.state.countryCode} </p>
      </div>
    );
  }
}
 2
Author: Избыток Сусликов, 2019-06-19 05:01:19

There was another question. I need to send data to the parent component, the child has a button

  render() {
return (
  <div>
    <button onClick={() => { this.props.updateCity(this.state.city)}}>Определить город</button>
  </div>
);

}

And how can I send without a button, without clicking on it?

 0
Author: Hudoi, 2019-06-28 08:23:24

And how can I send without a button, without clicking on it?

Render the function before return() in the same render-e, as an option:

render() {
    this.props.updateCity(this.state.city);

    return (
        <div> ... </div>
    );
}
 0
Author: Rikky, 2019-09-17 19:59:58