Reputation: 45
i have a search input and i hope to make a "live-search" i mean when the user change the value of the input-text the result update ! i use react-native and sqlite as a local database
Now the result is the function of "set_state" excute after the function of "search_user" ! when i put the user_id "2" i dont recive any result but when i delete the "2" i recive the result of "2" so i conclure that t hese two functions must excute the seconde after the first ! if you have an other solution or how to fix this problem please ?
searchUser = () => {
const { input_user_id } = this.state;
console.log(this.state.input_user_id);
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM table_user where user_id = ?',
[input_user_id],
(tx, results) => {
var len = results.rows.length;
console.log('len', len);
if (len > 0) {
this.setState({
userData: results.rows.item(0),
});
} else {
alert('No user found');
this.setState({
userData: '',
});
}
}
);
});
};
constructor(props) {
super(props);
this.state = {
input_user_id: '',
userData: '',
};
}
and this is my textinput
<Mytextinput
placeholder="Enter User Id"
onChangeText={input_user_id => {this.searchUser(this); this.setState({ input_user_id }); }}
style={{ padding:10 }}
/>
Upvotes: 4
Views: 123
Reputation: 66
Yes ! when you do
function(input_user_id) {
this.searchUser(this);
this.setState({ input_user_id })
}
both functions run in order, but setState is asynchronous.
So when you do
const { input_user_id } = this.state;
the state has not been updated yet.
As you can pass a callback function to setState,
you make sure that input_user_id will be updated before this.searchUser() is executed
this.setState({input_user_id }, () => this.searchUser(this))
Upvotes: 1
Reputation: 66
why do not you pass input_user_id directly to the function ? otherwise you can do
this.setState({input_user_id }, () => this.searchUser(this))
Upvotes: 3
Reputation: 488
setState in react is asynchronous
you can use callbacks to do something after setState has finished this way -
searchUser(callback_func) => {
//... code here
this.setState({
userData: '',
}, () => { callback_func(status); }); // status is not required, but you can signify failures this way
}
// now you can use searchUser like this -
searchUser(status => {
//do this when set state done
});
Upvotes: 2