Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

0

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

setClickFavIconArray([])
about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda