I am trying to filter through an array based on checkboxes. When these are ticked, it would show the elements with those attributes (viewable, reported etc). I am having issues with the filter function.
I tried using the forEach method, but that becomes messy with trying to keep the last checkboxes results the same. So I've decided to keep those values the same using state, then to filter the results based on the state. However I am being told 'Cannot read property 'state' of undefined' even though my console log shows the viewable and reported values as 1s or 0s. Not sure what's going wrong but would appreciate a solution to the problem, especially if I'm on the wrong track!
handleCheck = (e) => {
if (e.target.checked) {
this.setState ({
[e.target.name]: '1'
})
} else {
this.setState ({
[e.target.name]: '0'
})
}
console.log(this.state);
this.filterPosts();
}
filterPosts = () => {
this.setState ({
parentArray: this.props.parentResults
})
var filterArray = this.state.parentArray.filter(function(element) {
if (this.state.viewable===1 && this.state.reported===1) {
return element.viewable===1 && element.reportCount>0
} else if (this.state.viewable===1 && this.state.reported===0) {
return element.viewable===1 && element.reportCount===0
} else if (this.state.viewable===0 && this.state.reported===1) {
return element.viewable===0 && element.reportCount>0
} else if (this.state.viewable===0 && this.state.reported===0) {
return element.viewable===0 && element.reportCount===0
}
});
console.log(filterArray);
}
The parentArray comes from the props, and definitely works as I've been able to use forEach methods. I then alter state using checkboxes, and am trying to use this to modify the filter function.
Just want the posts that are viewable or reported to appear and disappear as you check the boxes. Cheers!