Ace_kous471
Ace_kous471

Reputation: 11

Invalid hook call. Hooks can only be called inside of the body of a function component while trying the search filter

Error said error occurred while trying to do a search filter using useState. i am a beginner developer recently started using react.js the code is as follows:

this is where i have loaded the product

loadSearchData(){
        getActiveProduct(null).then((response) => {
            if(response.code == API_SUCCESS){
                this.setState({
                    productList: response.data.product
                })
            }
        })
    }

this is where i have used the filter option for search data

getSearchData(){
        const [searchTerm, setSearchTerm] = useState('')
        const data = this.state.productList.filter((item)=>{
            if(item.name.toLowerCase().includes(searchTerm.toLocaleLowerCase()))
            return item
        }).map((item, index) => {
            return (
                <li key={index}>
                    <a  onClick={(e) => this._navigateShop(route.product_details + "/" + item.id)}>{item.name}</a>
                </li>
            )
        })
    }

this is where i want to display data

<div className="search-field collapse" id="searchToggle" >
      <input className="search-input" placeholder="Search..." type="text" onChange={event =>   {setSearchTerm(event.target.value)}} />
        <a type="button" data-toggle="collapse" data-target="#searchToggle" aria-controls="searchToggle" aria-expanded="false">
          <i className="icon_close search-close"></i>
        </a>
        <div className="search-dropdown">
             {this.getSearchData()}
        </div>
  </div> 

Upvotes: 1

Views: 88

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

You are using a class component, and hooks are not available there

If you want to add another searchTerm state, add another searchTerm to your state.


If you use a functional component

You can't declare a hook inside a function inside your function component, move it to the top of your function

const [searchTerm, setSearchTerm] = useState('')  // <--- Move this to the top of your component!

As follow Rules Of Hooks

Upvotes: 1

Related Questions