Home > Software design >  How to prevent React from rendering twice setState function?
How to prevent React from rendering twice setState function?

Time:01-24

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?

CodePudding user response:

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!

  • Related