Reputation: 359
I have created two inputs and i update the state using setState
. When i type in the input and then console.log
it doesn't log it straight away.
For example if i type "a n" into the input it will console log the "a" on the second key stroke...
I know that this.setState
doesn't update straight away and batch updates the state, but when i have done this in the past it has worked. Why isn't my input value updating with React?
How can i get my inputs to update straight away? I want this to happen as i need to use the input by the user as a search keyword and pass each input value to a function.
code:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
movieTitleSearch: "",
searchByYear: "",
};
}
handleOnChange = (event) => {
const { movieTitleSearch } = this.state;
const { searchByYear } = this.state;
this.setState({
...this.state, [event.target.name]: event.target.value,
},
() => {
if (movieTitleSearch || searchByYear > 1) {
this.props.movieSearch(movieTitleSearch, searchByYear);
}
console.log(movieTitleSearch) // does not update straight away in the console.
console.log(searchByYear) // does not update straight away in the console.
}
);
};
render() {
return (
<div>
<label>search film title</label>
<input
onChange={this.handleOnChange}
type="text"
name="movieTitleSearch"
placeholder="search by film"
value={this.state.movieTitleSearch}
/>
<label>search by year</label>
<input
onChange={this.handleOnChange}
type="text"
name="searchByYear"
placeholder="search by year"
value={this.state.searchByYear}
/>
</div>
);
}
}
UPDATED ONCHANGE FUNCTION
handleOnChange = (event) => {
const { movieTitleSearch } = this.state;
const { searchByYear } = this.state;
this.setState(
{
...this.state, [event.target.name]: event.target.value,
},
);
this.props.movieSearch(this.state.movieTitleSearch, this.state.searchByYear)
console.log(this.state.movieTitleSearch) // why when i type in the inputs does this not log to the console straight away?
console.log(this.state.searchByYear)
};
Upvotes: 0
Views: 205
Reputation: 1049
You are accessing the previous state when you use const movieTitleSearch
.
You have to use it like this.state.movieTitleSearch
, then you will get the updated state value.
handleOnChange = (event) => {
const { movieTitleSearch } = this.state;
const { searchByYear } = this.state;
this.setState({
...this.state, [event.target.name]: event.target.value,
},
() => {
if (movieTitleSearch || searchByYear > 1) {
this.props.movieSearch(this.state.movieTitleSearch, this.state.searchByYear);
}
console.log(this.state.movieTitleSearch)
console.log(this.state.searchByYear)
}
);
};
Also, I would suggest calling the movieSearch
outside of the setState
callback, because you already have its value with you inside event.target.value
Upvotes: 1