Frozencode
Frozencode

Reputation: 67

TypeError: item.name.toLowerCase(...).include is not a function reactjs

hello iam new with this reactjs, iam currently try some course at Egghead and when i try this topic about Use map to Create React Components from Arrays of Data i get some error , i dont understand cause i already have same code

import React from 'react'

class  Filter extends React.Component{
constructor(){
    super()
    this.state = {
        items : [],
        filter :""
    }
}

componentWillMount(){
    fetch('https://swapi.co/api/people/?format=json')
    .then(response => response.json())
    .then(({results: items})=>
          this.setState({items})  
    )
}

filter(event){
    this.setState({filter: event.target.value})
}

render(){
    let items = this.state.items
    console.log(items)
    if(this.state.filter){
        items = items.filter( item => 
        item.name.toLowerCase()
        .include(this.state.filter.toLowerCase()))
    }

    return(
        <div>
            {this.state.filter}
            <input type="text" onChange={this.filter.bind(this)}/>
            {items.map(item => <Org key={item.name} org={item}/>)}
        </div>
    )

}

    }
    const Org = (props) => <h4 >{props.org.name}</h4>

    export default Filter

this error show when i try filter it , its like i cant call array items with key name , that array get from api

Upvotes: 0

Views: 4604

Answers (2)

darth-coder
darth-coder

Reputation: 762

You can add a check if the item is of type string in case it's not.

Something like:

if (item && typeof item === "string") item.name.toLowerCase();

Because there's always a possibility that your array might be populated with elements other than of type string.

Upvotes: 0

Treycos
Treycos

Reputation: 7492

The function you are looking for is includes. You made a little typo

item.name.toLowerCase().includes(this.state.filter.toLowerCase()))

Upvotes: 3

Related Questions