Search code examples
javascriptreactjsreact-nativeecmascript-6es6-promise

React : Search Filter is not working Properly


I am fetching records from server through API , API was built in Loopback . Actually On every page I am showing 5 records , currently It working fine I can navigate next or prev through pagination button and on every page it showing 5 records . Problem is that when User type something in search box , record are fetching correctly but when user remove query from search box it break the application flow . I mean to say that It showing all data not like 5 . I want that when user search something and remove text from search box it might not break application flow it must show 5 records after do query search . I will provide code please have a look and help me to figure out if I made some mistake . I am beginner to React and does not have much knowledge to fix this problem . Thanks Code

    class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

Solution

  • The problem is that when you empty the searchbox, keyword becomes "". You then check str.indexOf("") returns 0 which means your filter operation returns all items (like you are seeing)!!!

    This returns everything when keyword is "":

     let filtered=this.state.allData.filter((item)=>{
          return item.companyName.indexOf(keyword) > -1
        });
    

    To fix it - simply return [] if keyword is empty ("")

    searchHandler(event){
        let keyword =event.target.value;
        let filtered=this.state.allData.filter((item)=>{
          return item.companyName.indexOf(keyword) > -1
        });
        if (keyword === "") {
          filtered = [];
        }
        this.setState({
          filtered
        })
      }