Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do:

handleChangeCompetitor(filterCompetitors) {
  this.setState((state) => ({
    competitors: state.competitors.includes(filterCompetitors)
      ? state.competitors.filter((fc) => fc !== filterCompetitors)
      : [...state.competitors, filterCompetitors],
  }))
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda