Reputation: 445
I'm using this class to display and filter a list. This class also trigger a search.
My problem is it seems that the setState function is not immediate.
FriendActions.getSearchList(this.state.search);
If I comment this actions. The console.log will print the state as is it should be. If no the 'search' state will "disappear".
I think maybe a change event is fire before the state is changed. But i have really no clue.
I hope I've made myself clear. If not feel free to ask me more information.
onSearch(event){
this.setState({search: event.target.value});
if (this.state.search !== '')
FriendActions.getSearchList(this.state.search);
}
class FriendList extends React.Component {
constructor(props) {
super(props);
this.state = FriendStore.getState();
this.onChange = this.onChange.bind(this);
this.filterByUsername = this.filterByUsername.bind(this);
// limit this function every 200 ms
this.onSearch = debounce(this.onSearch, 200);
}
componentDidMount () {
FriendStore.listen(this.onChange);
FriendActions.getFriendsList();
}
componentWillUnmount() {
FriendStore.unlisten(this.onChange);
}
onChange(state) {
console.log(state);
this.setState(state);
}
onSearch(event){
this.setState({search: event.target.value});
if (this.state.search !== '')
FriendActions.getSearchList(this.state.search);
}
Upvotes: 0
Views: 146
Reputation:
You need to change your logic. Something like this should work:
onSearch(event){
var search = event.target.value;
if (search !== '') {
FriendActions.getSearchList(search);
}
this.setState({search: search}); // w/ ES6: this.setState({search});
}
You are correct that setState
is not immediate. The reason is that you can have many setState
calls in your code. React will run render
on a setState
. For performance reasons it waits until all setState
calls are done then renders.
Alternative solution (not recommended): Set your state manually
this.state = 'whatever';
and update yourself
this.forceUpdate();
Upvotes: 1