Reputation: 1785
I feel like Im going crazy here.....
I type in "x" to the searchbar but this.setState({ filter: text });
is not updating state.... console.log(this.state.filter);
gives me a value of '' (its initial value set in constructor).
I can see the value of text variable is x...but its just not updating the filter state.
constructor(props) {
super(props);
this.state = {
timer: 30 * 60,
lat: 0,
lng: 0,
loading: false,
data: [],
pagetoken: null,
refreshing: false,
waiting4answer: false,
placeName: null,
placeUri: null,
filter: '',
};
}
renderHeader = () => {
if (this.state.waiting4answer === false) return null;
return (
<SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={(text) => {
this.setState({ filter: text });
console.log(this.state.filter);
this.searchFilterFunction();
}}
autoCorrect={false}
/>
);
};
Upvotes: 3
Views: 11109
Reputation: 850
use the setState callback to get the updated state immediately after setting it
this.setState({ filter: text }, () => {
console.log(this.state.filter);
});
react setState is asynchronous
Upvotes: 1
Reputation: 28539
The state is updating, it's just the way that you are checking and using the updated state is flawed.
State is asynchronous, it takes time for the state to set. The problem you are encountering is that you are calling setState
and then immediately logging the value from state. Unfortunately when you do this the state will not have updated by this time you log it, so you are getting the previous value.
If you want to use the value of state that you have just set then you need to use the callback
function that setState
has. this.setState({key: value}, callback)
This callback allows you to run functions after the state has been set. You can use it in the following way:
this.setState({filter: text}, () => {
// put the things you wish to occur after you have set your state.
console.log(this.state.filter);
// I am guessing your searchFilterFunction requires the updated filter value in state
// so put that here too
this.searchFilterFunction();
});
This means that once you set the value of filter
in the state and the state has updated to reflect that value it will then run the callback
, so it will log the value of filter
that is now in state, and then it will run the searchFilterFunction
.
You can read more about state in this series of great articles by Michael Chan
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
Upvotes: 6