Reputation: 2577
I make an API call with componentDidMount
. The code delivers me the results as the page renders. However, I don't seem to be able to update its values and pass it into ComponentDidMount. My code is below.
getInitialState: function(){
return {main: '', place: 'London, UK', weather: [{icon: ''}] }
},
componentDidMount: function(){
var comp = this;
$.get("http://api.openweathermap.org/data/2.5/weather?q="+comp.state.place+"&appid=abunchofnumbers", function(data){
comp.setState(data);
});
},
setit: function(){
this.setState({place: document.getElementById('stuff').value});
console.log(this.state.place);
},
render: function(){
return (<div>
<p>{this.state.name}</p>
<p>{this.state.main.temp}</p>
<p>{this.state.weather[0].icon}</p>
<input type="text" id="stuff" />
<input type="submit" value="submeet" onClick={this.setit}/>
</div>);
}
In addition, it takes two clicks to console.log the most recent entry in place
. Clicking it only once returns the value it was before.
EDIT: The following adjustments have since been made to the code, and work as they should. However, when data is re-rendered, it has a strange flicker effect.
callthebase: function(){
var comp = this;
$.get("http://api.openweathermap.org/data/2.5/weather?q="+comp.state.place+"&appid=1333982caee02b04d765f15ec51bf10d", function(data){
comp.setState(data);
});
},
componentDidMount: function(){
return this.callthebase();
},
componentDidUpdate:function(){
return this.callthebase();
},
setit: function(){
this.setState({place: document.getElementById('stuff').value});
},
render: function(){
return (<div>
<p>{this.state.name}</p>
<p>{this.state.main.temp}</p>
<p>{this.state.weather[0].icon}</p>
<input type="text" id="stuff" />
<input type="submit" value="submeet" onClick={this.setit}/>
</div>);
}
Upvotes: 0
Views: 3920
Reputation: 14768
If you want to respond to a change in state, you should define a componentDidUpdate
method and check if place
changes. If it does, make a new request.
I recommend moving your GET
request code out of componentDidMount
and into a new function. Then call that function in componentDidMount
and in componentDidUpdate
.
Also, you shouldn't need to use getElementById
in your component. Instead, you should pass onChange
and value
props to your input and store the input's value in your component's state.
See: https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate
Upvotes: 3