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

How to prevent React from rendering twice setState function?

I called a function that changes the state of a boolean property of an object, but since React is rendering my SetState function twice, the value goes from False to True and then from True to False, so i end up getting the same value i had before calling the function.

const updateCheck = () => {
    setTodoList((prev) => {
      const prevAux = [...prev];
      const pos = prevAux.indexOf(item);
      prevAux[pos].checked = !prevAux[pos].checked;
      return prevAux;
    });

This is where i call the function from:

<div
  onClick={updateCheck}
  className={
    item.text !== ""
      ? `${css.liButton} ${css.check} ${
          item.checked ? css["check-true"] : css["check-false"]
        }`
      : css.none
  }
>
  <FontAwesomeIcon className={css.icon} icon="fa-check"></FontAwesomeIcon>
</div>

Does someone know how i can solve it or whether i’m making a mistake?

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

>Solution :

Try this implementation:

setTodoList((prev) => {
  return prev.map((todo) => {
    if (todo === item) {
      return { ...todo, checked: !todo.checked };
    }
    return todo;
  });
});

Let me know if it worked!

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