javascript - React API call don't change state -


i trying create react weather app. in app can type name of city , shows temperature. after caloing api state dont want change other city object (in coponentdidmount method - "obje" state).

import react, { component } 'react'; import api './api.js';  class app extends component {   constructor(props) {     super(props);     this.state = {       obje: {},       inputvalue: 'paris'     }   }   componentdidmount() {     var rooturl = "http://api.openweathermap.org/data/2.5/weather?q=";     var city = this.state.inputvalue     var key = "&appid=aa32ecd15ac774a079352bfb8586336a";       fetch(rooturl + city + key)         .then(function(response) {             return response.json();         }).then(d => {           this.setstate({obje:d})         });    }    handlechange(event) {     event.preventdefault();      this.setstate({inputvalue: this.refs.inputval.value});     console.log(this.refs.inputval.value);   }   render() {     return (       <div>        {this.state.obje.name}        <form action="" method="" onsubmit={this.handlechange.bind(this)}>       <input ref="inputval" type="text" />       <input type="submit" />     </form>       </div>     );   } }  export default app; 

componentdidmount called once - when component mounts. state change not trigger code again, therefore xhr request not made again. split out xhr logic own method , call in both places, example:

import react, { component } 'react'; import api './api.js';  class app extends component {   constructor(props) {     super(props);     this.state = {       obje: {},       inputvalue: 'paris'     }   }   getweather() {       var rooturl = "http://api.openweathermap.org/data/2.5/weather?q=";       var city = this.state.inputvalue;       var key = "&appid=aa32ecd15ac774a079352bfb8586336a";         fetch(rooturl + city + key)           .then(function(response) {               return response.json();           }).then(d => {             this.setstate({obje:d})           });   }   componentdidmount() {      this.getweather();   }    handlechange(event) {     event.preventdefault();      this.setstate({inputvalue: this.refs.inputval.value}, () => {         this.getweather();     });     console.log(this.refs.inputval.value);   }   render() {     return (       <div>        {this.state.obje.name}        <form action="" method="" onsubmit={this.handlechange.bind(this)}>       <input ref="inputval" type="text" />       <input type="submit" />     </form>       </div>     );   } }  export default app; 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -