So far I can only search an element of the array if I type the exact name present in my api, in this my api has an array with 20 positions and if I type exactly the name of the element I search it returns an array with 19 positions with undefined and 1 position with the array found, what I want to do and search while I type instead of searching only when I type the full name. After my search I try to change the state of a component so that it is rendered only with the value fetched, but this does not happen, if anyone knows I am very grateful.
updated code import data from "../sample_data/recipes.json"; class App extends Component { constructor(props) { super(props); this.state = { searchString: [] }; } componentDidMount() { this.setState({ searchString: data.results }) } onChange(fieldName) { if (fieldName === '' || fieldName === null) this.setState({ searchString: data.results }); var indexes = data.results.filter((item, i) => { return item.title.toLowerCase().indexOf(fieldName.toLowerCase()) !== -1; }) this.setState({ searchString : indexes }); } render() { return ( <div className="App"> <Navbar onChange={this.onChange.bind(this)} /> <div className="container mt-10"> <div className="row"> {<RecipeItem list={this.state.searchString} />} </div> </div> </div> ); } } export default App;
Advertisement
Answer
I suppose that you want some kind of filtering while you’re typing:
can you try this ? :
onChange(fieldName) { if (fieldName === '' || fieldName === null) this.setState({ searchString: data.results }); var filteredItems = data.results.filter((item, i) => { return item.title.toLowerCase().indexOf(fieldName.toLowerCase()) === -1; }) this.setState({ searchString : filteredItems }); }
Explanation :
What is requested is to not display items that contains typed letters, to do that, you can use filter items with filter
method and return only the items which doesn’t have the typed letters in the title (using the indexOf
method).