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

155
Vistas
Why doesn't my useState array get emptied?

My useState:

const [valuesToSearchFor, setValuesToSearchFor] = useState([]);

I have the following search input field with an onChange:

onChange={() => {
  setValuesToSearchFor(
  valuesToSearchFor.includes(value)
    ? valuesToSearchFor.filter(val => val !== value)
    : [...valuesToSearchFor, value]
  );
}}

This changes some data on my page like so:

{data.elements.filter((val) => {
  if(valuesToSearchFor.includes(val.name.toLowercase()){
      return val
  }
}

The only issue is when I delete the input field, it doesn't reflect in the array. Question How can I empty out valUesToSearchFor so another search can be typed out in the input?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Hard to say without seeing more of your code, but you should destructure your filtered valuesToSearchFor. Otherwise you're trying to modify a state prop directly

onChange={(e) => {
  const value = e.target.value;
  setValuesToSearchFor(
    valuesToSearchFor.includes(value)
    ? [...valuesToSearchFor.filter((val) => val !== value)]
    : [...valuesToSearchFor, value]
  );
}}

As @Amiratak88 points out, this is going to push a new value to your array on every keystroke.

Again, not sure what you're trying to do, but you might opt to use buttons that update/reset your state.

const MyComponent = () => {
  const [searchValue, setSearchValue] = useState("");
  const [valuesToSearchFor, setValuesToSearchFor] = useState([]);

  return (
    <>
      <input
        onChange={(e) => {
          setSearchValue(e.target.value);
        }}
      />
      <button
        onClick={(e) => {
          e.preventDefault();
          // update valuesToSearchFor with all unqiue values, including the current searchValue
          setValuesToSearchFor([...new Set([...valuesToSearchFor, searchValue])]);
        }}
      >
        Search
      </button>
      <button
        onClick={(e) => {
          e.preventDefault();
          setValuesToSearchFor([]);
        }}
      >
        Reset
      </button>
    </>
  );
};


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