0

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.

1
  • 2
    should be ? state.competitors.filter(i => i ... and : [ ...state.competitors, filterCompetitors ] Commented May 10, 2022 at 21:26

1 Answer 1

1

You can do:

handleChangeCompetitor(filterCompetitors) {
  this.setState((state) => ({
    competitors: state.competitors.includes(filterCompetitors)
      ? state.competitors.filter((fc) => fc !== filterCompetitors)
      : [...state.competitors, filterCompetitors],
  }))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.