Tested
Tested

Reputation: 789

search results are dislayed on second click n not for the first react js

M doing asearch what happens is search results are dislayed on second click n not for the first react js i dont unstand whats happenindg on the second click this is not dynamic have used statiic value

any help is appreciated

handleChange(e) {
  this.setState({ value: e.target.value });
}

handleSubmit(e) {
  e.preventDefault();
  this.setState({
    listArr: this.props.list.filter(e1 => e1 === this.state.value),
  });
  this.props.searchItem(this.state.listArr);
}

render() {
  return (
    <div>
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          placeholder="Search..."
          onChange={this.handleChange}
        />
        <input type="Submit" value="sech" />
      </form>
    </div>
  );
}

what is it displaying onto second click

Upvotes: 0

Views: 353

Answers (1)

devserkan
devserkan

Reputation: 17608

setState is asynchronous, so after you set your state other parts of your function can't catch up. Try with a callback with setState.

handleSubmit(e){   
     e.preventDefault();
     this.setState({
         listArr:this.props.list.filter(e1=> 
         (e1===this.state.value))
     }, () => this.props.searchItem(this.state.listArr) );  
}

Update after comments

As I tried to explain, setState is asynchronous. It does not update the state immediately. First, you set your state with filtering. But when you invoke searchItem function, setState is still trying to update the state, it does not finish its job. So, your listArr is still empty or not updated at that time. Hence, your search does not work.

But why does it work in the second time? Because when you hit the button for the second time setState has already finished its job, there is actually a listArr now. So, your search works.

Here, callback function in setState waits for the update, then invokes what you provide to it.

Upvotes: 2

Related Questions