searchProject(title, language, length, experience) {
if (title !== "") {
const projects = this.state.projectList.filter(
p => p.title === title
);
this.setState({projectList : projects});
}
if (language !== "") {
const projects = this.state.projectList.filter(
p => p.language === language
);
this.setState({projectList : projects});
}
if (length !== 0) {
const projects = this.state.projectList.filter(
p => p.length === length
);
this.setState({projectList : projects});
}
if (experience !== "") {
const projects = this.state.projectList.filter(
p => p.experience === experience
);
this.setState({projectList : projects});
}
}
I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!
setStatethe entire component re-renders and I'm assuming that this code will be called again. That's why the projectList only updates the last parameter. In order to do all of it, I suggest making project alet projectand filter upon the filters.Let me know if you want me to elaborate more @Adam Lau.