Reputation: 119
http://codepen.io/anon/pen/KNEzOX?editors=0010
I have component A that does the fetch and render the list. I have component B that accept the user input. How do I fire component A from component B? I guess my structure is wrong.
const Profiles = React.createClass({
getInitialState(){
return {profiles: []}
if(!this.props.username){
return false;
}
fetch('https://api.github.com/search/users?q=' + this.props.username)
.then(function(response) {
return response.json()
}).then(function(json) {
this.setState({profile: json.items})
})
},
render(){
return (
<ul>
{
this.state.profiles.map(profile =>
<li key={profile.id}>profile.name</li>
)
}
</ul>
)
}
})
const Input = React.createClass({
getInitialState(){
return {username:''}
},
handleInputChange(e){
this.setState({username:e.target.value})
},
handleSearch(){
if(!this.state.username){
alert('username cannot be empty');
return false;
}
//call profile component and pass username to it?
},
render() {
return(
<div>
<input type="text" placeholder="github username" onChange={this.handleInputChange} value={this.state.username} />
<button onClick={this.handleSearch}>Search</button>
<Profiles username={this.state.username} />
</div>
)
}
});
Upvotes: 1
Views: 810
Reputation: 33399
First off:
getInitialState(){
return {profiles: []}
if(!this.props.username){
return false;
}
fetch('https://api.github.com/search/users?q=' + this.props.username)
Fetch will never get executed here because of the return. Put the return at the end.
Second, what you need here is for it to fetch when the component receives new props. What i would do is add a new method to the class that will fetch, and call it both from getInitialState
and componentWillReceiveProps
. So:
getInitialState(){
if(!this.props.username){
return false;
}
this._fetchData();
return {profiles: []}
},
componentWillReceiveProps(){
this._fetchData();
},
_fetchData(){
fetch('https://api.github.com/search/users?q=' + this.props.username)
.then(function(response) {
return response.json()
}).then(function(json) {
this.setState({profile: json.items})
})
},
The issue is that the component already exists, so getInitialState
doesn't get called. It just has to update itself.
Upvotes: 1