Im trying to implement a simple Filter function in React. I got 6 Buttons and every Button has a value. A button can be selected or not selected. I just need to get the all the selected values. My idea was to write the value into an array when a button is clicked. When the button is clicked a second time, the item is removed from the array. I tried a function which gets the array and the item to be toggled. It checks if the array already has the item. If yes then it uses filter to remove it. If not it uses the spread operator to create a new array containing the values of the provided array plus the new item. My Component and the Function looks like that:
export default class App extends Component {
constructor(props) {
super(props);
this.handleChangeCompetitor = this.handleChangeCompetitor.bind(this);
this.state = {
competitors: [],
};
}
handleChangeCompetitor(filterCompetitors) {
this.setState(state => {
const competitors = state.competitors.includes(filterCompetitors)
? competitors.filter(i => i !== filterCompetitors)//remove items
: [ ...competitors, filterCompetitors ]; // add item
return {
competitors,
};
});
}
}
The problem is its not working and i got this Error:
Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
Has someone an idea why its not working or whether the approach makes any sense at all.
You can do:
handleChangeCompetitor(filterCompetitors) {
this.setState((state) => ({
competitors: state.competitors.includes(filterCompetitors)
? state.competitors.filter((fc) => fc !== filterCompetitors)
: [...state.competitors, filterCompetitors],
}))
}