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

336
Visualizações
How to filter useState hook Array and push & pull data to that array?

I am searching for filter React useState hook array. Not getting any answer. Please help me.

I define useState string array-

const [filterBrand, setFilterBrand] = useState<string[]>([]);

Here is my function for filtering this array and push, pull data-

const brandHandler = (item: string) => {
    //Here I need if filterBrand already have the 
      item then remove it and update the state, 
      else add the item to this array and update 
      the state
}

Here I need to check if item already have in filterBrand. then remove it from filterBrand and update the State. Else I need to add the item to filterBrand and update the State

I already tried it-

const brandHandler = (item: string) => {
    const items: string[] = [...filterBrand];
    if (!filterBrand.includes(item)) {
        items.push(item)
    } else {
        return items.filter(f => f !== item)
    }
    setFilterBrand(prevState => ({ ...prevState, ...items }));
}

But getting this error-

Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Do this

// setFilterBrand(prevState => [ ...prevState, ...items ]); would work
setFilterBrand(items) // likely what you want instead

instead of

setFilterBrand(prevState => ({ ...prevState, ...items }));

You are transforming your array into an object for some reason here

Full code:

const brandHandler = (item: string) => {
    let items: string[] = [...filterBrand];
    if (!filterBrand.includes(item)) {
        items.push(item)
    } else {
        items = items.filter(f => f !== item)
    }
    setFilterBrand(items);
}
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