Home > Back-end >  React input onChange method search the term after the first character
React input onChange method search the term after the first character

Time:01-10

I am new in React and i have a problem with the searching while typing on the input of search bar. The problem is when type a term on the searchbar, it triggers the value after the first character like let's say I want to search for words starts with "f" but when I type "f" it doesn't trigger the value "f" at first. So you have to type another "f" so that it triggers.

Here is my code:

import React from "react";
import { SearchBar } from "./SearchBar";

export default class App extends React.Component {
  state = { result: [] };
  onTermSearched = (term) => {
    console.log(term);
    // Term is searched from the records Api and returns the list.
    //   const response = await elastic.get('/records', {
    //     params: {
    //         q: term,
    //     },
    // })

    // this.setState({ result: response.data })
  };
  render() {
    return (
      <div className="ui container">
        <SearchBar onInputChange={this.onTermSearched} />
      </div>
    );
  }
}

export class SearchBar extends React.Component {
    state = { term: '' }
    onInputChange = (event) => {
        event.preventDefault()
        this.setState({ term: event.target.value })
        this.props.onInputChange(this.state.term)
    }

    render() {
        return (
            <div className="search-bar">
                <div className="ui form">
                    <div className="field">
                        <input
                            type="text"
                            value={this.state.term}
                            onChange={this.onInputChange}
                        />
                    </div>
                </div>
            </div>
        )
    }
}

codesandbox

please check the console while you type. You will understand my problem.

CodePudding user response:

try to use setState second parameter which is an optional callback function, that will be executed when setState is completed, like this:

this.setState({ term: event.target.value }, ()=> {
  this.props.onInputChange(this.state.term)
})

CodePudding user response:

This will update your term state and onInputChange props at the same time.

onInputChange = (event) => {
   event.preventDefault();
   this.setState((state, props) => {
     props.onInputChange(event.target.value);

     return { term: event.target.value };
   });  
};
  •  Tags:  
  • Related