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

120
Visualizações
UseState how to set an Array back to empty?

I'm trying set clickFavIconArray back to an empty array with the hook.

Basically, the setClickFavIconArray has a list of IDs the showFavIcon() checks that ID and if it contains the same ID I want to remove it from the array and update the setClickFavIconArray to the new Array.

However, it just seems to be adding on to the original clickFavIconArray no matter what. Is there a way to clear the clickFavIconArray state back to an [] empty array?

Some help here would be awesome.

const [clickFavIconArray, setClickFavIconArray] = useState([]);

    function showFavIcon(id){
        if (clickFavIconArray.includes(id)) {
            const newArray = clickFavIconArray.filter(item => !id.includes(item))
            setClickFavIconArray(newArray)
        }
            setClickFavIconArray([...clickFavIconArray, id])
    }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Simply pass the new value of empty array to setClickFavIconArray():

setClickFavIconArray([])
about 4 years ago · Juan Pablo Isaza Relatório

0

To make sure that the id is not immediately added to the array again, add a return statement inside the if-statement.

const [clickFavIconArray, setClickFavIconArray] = useState([]);

function showFavIcon(id){
    if (clickFavIconArray.includes(id)) {
        const newArray = clickFavIconArray.filter(item => !id.includes(item));
        setClickFavIconArray(newArray);
        return; // make sure that the next line is not executed
    }
    setClickFavIconArray([...clickFavIconArray, id])
}
about 4 years ago · Juan Pablo Isaza Relatório

0

There are two issues with the code

  1. filter function seems to be invalid it should be replaced with
clickFavIconArray.filter(item => id != item)
  1. You are adding id again to the array with this
setClickFavIconArray([...clickFavIconArray, id])

If you want to remove id, there is no need for this line in your code. However you can always set clickFavIconArray to an empty array state using this code:

setClickFavIconArray([])
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