Reputation: 323
While attempting to add the functionality to my project of saving the term in the Search Bar through refreshing your browser, I got it to where things were being saved correctly. The only issue came up with me saving the term in the "handleTermChange" method of the component, so it would pass undefined if you do not change the term in any way before searching. I attempt to bypass this in the "search" method by checking if the state for the term is empty (as it's live updated with the handleTermChange method). The conditional checking if the term in the state is empty works fine, as you enter it when you search without changing anything in the SearchBar. The first console.log prints out the variable fine, but the second console log still prints out an empty string, I'm probably missing something small, but I can't tell, I'm too tired to see little things.
search() {
if (this.state.term === '') {
const savedTerm = sessionStorage.getItem("inputValue");
console.log(savedTerm);
this.setState({term: savedTerm});
console.log(this.state.term);
}
this.props.onSearch(this.state.term);
}
Upvotes: 1
Views: 42
Reputation: 1479
This call is asynchronous, try adding a callback function before accessing the property like:
search() {
if (this.state.term === '') {
const savedTerm = sessionStorage.getItem("inputValue");
console.log(savedTerm);
var thisState = this;
this.setState({term: savedTerm}, function () {
console.log(thisState.state.term);
});
}
this.props.onSearch(this.state.term);
}
Upvotes: 0
Reputation: 2547
Does this work ? Because of the state updates could be asynchronous, you can't be sure that term will be savedItem without the callback.
Doc here.
search() {
if (this.state.term === '') {
const savedTerm = sessionStorage.getItem("inputValue");
console.log(savedTerm);
this.setState({term: savedTerm}, () => {
console.log(this.state.term);
this.props.onSearch(this.state.term);
});
} else {
this.props.onSearch(this.state.term);
}
}
Upvotes: 3