• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

161
Views
How to toggle an array item in React State

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.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can do:

handleChangeCompetitor(filterCompetitors) {
  this.setState((state) => ({
    competitors: state.competitors.includes(filterCompetitors)
      ? state.competitors.filter((fc) => fc !== filterCompetitors)
      : [...state.competitors, filterCompetitors],
  }))
}
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error