Reputation: 189
I'm currently working with the Soundcloud API and I'm trying to store the users that are returned into an array and then setState the array onto the parent object. The problem is when I console.log the updated state it shows it contains an array but it is empty. Below is an example of my code:
var SearchBar = React.createClass({
getInitialState: function(){
return {search : '',
avatar : '',
}
},
onChange: function(e){
e.preventDefault();
this.setState({search: e.target.value});
console.log('does this work', this.state.search)
},
onClick: function(e){
e.preventDefault();
},
getData: function(){
var userAv = [];
SC.get('/users', { q: this.state.search, limit: 10 }, function(users){
_.each(users, function(obj){
userAv.push(obj);
});
console.log('What is userAv', userAv);
})
this.setState({ avatar: userAv}, function(){
console.log('What is this.state.avatar', this.state.avatar)
});
},
render: function(){
return (
<div id='search-container'>
<input
onChange={this.onChange}
id='search-bar'
type = 'text'
value={this.state.search}
placeholder = 'Search For Artist here'
/>
<button
id="search-button"
onClick={this.getData}
type = 'button'>
Submit
</button>
<UserList />
</div>
)
}
});
Upvotes: 2
Views: 41
Reputation: 77482
You are trying get values from async request outside of callback that is wrong, move setState
inside callback
SC.get('/users', { q: this.state.search, limit: 10 }, function(users) {
this.setState({ avatar: users });
}.bind(this));
also chnage avarar
in getInitialState
to Array
from String
Upvotes: 1