I am trying to have a search bar which updates the set of json entries depending upon query. Here's the code that displays the video list (<Videos videos={this.state.data}/>). When the page loads, I want to call <Videos videos={this.state.data}/>, but after this query from search bar should update this list. My search functionality is not working for some reason.
class App extends Component {
state = {
query: "",
data: [],
filteredData: []
};
handleInputChange = event => {
const query = event.target.value;
this.setState(prevState => {
const filteredData = prevState.data.filter(element => {
return element.title.toLowerCase().includes(query.toLowerCase());
});
return {
query,
filteredData
};
});
};
getData = () => {
fetch('http://localhost:3000/api/videos')
.then(response => response.json())
.then(data => {
const { query } = this.state;
const filteredData = data.filter(element => {
return element.title.toLowerCase().includes(query.toLowerCase());
});
this.setState({
data,
filteredData
});
});
};
componentWillMount() {
this.getData();
}
render() {
return (
<div className="searchForm">
<form>
<input
placeholder="Search for..."
value={this.state.query}
onChange={this.handleInputChange}
/>
</form>
<Videos videos={this.state.data}/>
<div>{this.state.filteredData.map(i => <p>{i.name}</p>)}</div>
</div>
);
}
}
I am new to react, any pointers will be appreciated.