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

150
Vistas
My typescript function doesn't work without unused useState

I have two simple functions for adding and removing items to array

Function isInComparator() should check if item based on id read from checkbox value is in array or not and I need to change checkbox title to "remove", or "add"

It works with this code, but when I delete setLabelValue(value); row, it stops working and I don't understand why, because I am not even using it now

export const ProductItemBox = ({
      product,
    }: ProductProps): JSX.Element => {
      const [labelValue, setLabelValue] = useState("");
      let idsToCompare: string[] = [] || "";
      let productId: string;
      let isChecked = false;
      let value = "";
    
  const handleComparator = (productId: string) => {
    if (idsToCompare.includes(productId)) {
      idsToCompare = idsToCompare.filter((e) => e !== productId);
    } else {
      idsToCompare.push(productId);
    }

    setLabelValue(value);
  };

  const isInComparator = (productId: string) => {
    if (idsToCompare.includes(productId)) {
      value = "remove";
      isChecked = true;
    } else {
      value = "add";
      isChecked = false;
    }
    return isChecked;
  };
    <li key={product.productId}>
            <div className="comparator-form">
              <input
                type="checkbox"
                id={product.productId}
                value={product.productId}
                defaultChecked={isInComparator(product.productId)}
                onChange={() => handleComparator(product.productId)}
              />
              <label htmlFor={product.productId}>{value}</label>
            </div>
    </li>
  );
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This happens because setting state causes rerender of your component and when you don't set it the component does not rerender. You need to make idsToCompare a state variable and set it with setState, not just push to the array

You can learn everything you need to know about state here

about 4 years ago · Juan Pablo Isaza Denunciar

0

As @Marat said above, I am just providing you the same solution but in details.

export const ProductItemBox = ({
      product,
    }: ProductProps): JSX.Element => {
      const [labelValue, setLabelValue] = useState("");
      // as you can use useState hook with typeScript rules 
      const [idsToCompare,setIdsToCompare ]= useState<string[]>([]);
//      let idsToCompare: string[] = [] || "";
      let productId: string;
      let isChecked = false;
      let value = "";
    
  const handleComparator = (productId: string) => {
    if (idsToCompare.includes(productId)) {
      idsToCompare = idsToCompare.filter((e) => e !== productId);
    } else {
      // set the idsToCompare
      setIdsToCompare(oldArray => [...oldArray, productId]);
      // idsToCompare.push(productId);
    }

    // setLabelValue(value);
  };

  const isInComparator = (productId: string) => {
    if (idsToCompare.includes(productId)) {
      value = "remove";
      isChecked = true;
    } else {
      value = "add";
      isChecked = false;
    }
    return isChecked;
  };
    <li key={product.productId}>
            <div className="comparator-form">
              <input
                type="checkbox"
                id={product.productId}
                value={product.productId}
                defaultChecked={isInComparator(product.productId)}
                onChange={() => handleComparator(product.productId)}
              />
              <label htmlFor={product.productId}>{value}</label>
            </div>
    </li>
  );
};

Let me know if this solve the issue.

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