React js fetch API with componentDidMount()

Try this

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      wheather: null
    };
  }

  fetchData() {
    fetch("http://localhost:3000/rochelle-17.json")
      .then((response) => {
        return response.json();
      })
      .then((obj) => {
        //console.log('javascript object: ', obj)
        this.setState({ wheather: obj });
      });
  }
  componentDidMount() {
    console.log("Le composant App est monté sur le DOM !");
    this.fetchData();
  }
 render() {
    return (
      <div>
        {this.state.wheather
          && <div key={this.state.wheather.city_info.name}>{this.state.wheather.city_info.name}</div>
        }
        Hello World !
        <button /*onClick={() => this.fetchData()}*/> Click me !</button>
      </div>
    )
  }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top