Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
};

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading