Reputation: 509
Good Day, I am making a reactjs search filter using the filter method, my problem is everytime I pressed the backspace it doesn't get back to the original state or the state that I've set in the componentdidMount after ajax call, why is my state not updating back to the state that I've assigned in the componentDidMount?
This is my code.
class FilterInputs extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.onSubmit = this.onSubmit.bind(this);
}
searchHandler(event) {
event.preventDefault();
let itemss = this.state.items;
let searcjQery = event.target.value.toLowerCase();
let x = itemss.filter(el => {
let searchValue = el.rocket.rocket_name.toLowerCase();
return searchValue.indexOf(searcjQery) !== -1;
})
this.setState({
items: x
});
}
componentDidMount() {
axios.get(`http://localhost:8001/api`).then(res => {
const missions = res.data;
missions.map(item => {
const xx = item.rocket.rocket_name;
});
this.setState({
items: missions
});
});
}
May I know, on what I did wrong? Thank you in advance.
Upvotes: 0
Views: 662
Reputation: 11770
Lets set a filter in our state
named rocketNameQuery
and render based on that query.
I've changed the code to make it more readable.
class FilterInputs extends Component {
constructor(props) {
super(props);
this.state = {
missions: [],
// set our filter condition
rocketNameQuery: '',
};
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount() {
axios.get('http://localhost:8001/api')
// extract data to a variable named missions and set our state
.then(({ data: missions }) => {
this.setState({ missions });
});
}
searchHandler(event) {
event.preventDefault();
const rocketNameQuery = event.target.value.toLowerCase();
// update rocketNameQuery leaving state.missions untouched
this.setState({ rocketNameQuery });
}
checkFilterQuery(mission, rocketNameQuery) {
return mission.rocket.rocket_name.toLowerCase() === rocketNameQuery;
}
render() {
const { missions, rocketNameQuery} = this.state;
return !rocketNameQuery
? missions.map(mission => <div key={/* Add a unique key */}>{/* render logic */}</div>)
: (
<div>
// check if our item rocket name match our rocketNameQuery
{missions.map(mission => this.checkFilterQuery(mission, rocketNameQuery)
// match ? render logic
? <div key={/* Add a unique key */}>{/* Your render logic here */}</div>
// no match ? return null which will render nothing
: null
))}
</div>
);
}
}
Upvotes: 1