Gowtham Koushik
Gowtham Koushik

Reputation: 274

Using search in react js

I want to filter content based on the input typed, I don't know where did I go wrong. Whenever I typed my input it just doesn't filter the content instead of that it is showing all the content there.

  function searchingFor(searchingTerm) {
        return function(x){
            console.log("searching",x);
            return x.name.toLowerCase().includes(searchingTerm.toLowerCase())|| searchingTerm;
        }
    }

    class Main extends React.Component{

        componentWillMount(){
            this.props.fetchTopicsTableContent(this.state.sortBy,'ASC',0,this.props.match.params.Occupation).then(result=> (this.setState({rows:result.payload.data})))
            this.props.countTableContent(this.props.match.params.Occupation).then(result=>(this.setState({count:result.payload})));
        }

        constructor(props){
            super(props);

            this.state={
                searchTerm:"",
                rows:""
            }
        }

    searchHandler(e){
            this.setState({searchTerm:e.target.value})
            // console.log("rows",this.state.rows)
            {this.state.rows.filter(searchingFor(this.state.searchTerm)).map(item=>{
                console.log(item);
                 // this.setState({rows:item})
            })}
        }

    render(){
        return(
            <form>
               <input type="text"
                  value={this.state.searchTerm}
                  onChange={this.searchHandler.bind(this)}
                />
            </form>);}}

Upvotes: 0

Views: 346

Answers (3)

Chandan Bhandari
Chandan Bhandari

Reputation: 217

your searchingFor() function is wrong. Make the provided changes:

this.state.rows
.filter(item => item.name.toLowerCase().indexOf(searchingTerm.toLowerCase()) > -1)
.foreach(item => console.log(item));

You can use the spread operator to save the data

Upvotes: 0

Hitakshi Mahajan
Hitakshi Mahajan

Reputation: 61

The JavaScript operator || is defined to return the left value if it evaluates to a truthy value, otherwise the right value instead of returning true itself. So try replacing this

return x.name.toLowerCase().includes(searchingTerm.toLowerCase())|| searchingTerm;

with

return x.name.toLowerCase().includes(searchingTerm.toLowerCase())|| false;

Upvotes: 1

RomanRem
RomanRem

Reputation: 26

this.setState({searchTerm:e.target.value}) #setState is async operation and if you want to complete action how this operations will finish.

You should use callback function as for the 2d argument: this.setState({searchTerm:e.target.value}, () => {...here is your code})

Upvotes: 1

Related Questions