1

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?

4
  • Can you show us how you call this code? If it's from, say, a click event, i would not expect it to be called twice. Commented Jan 23, 2023 at 20:16
  • yes, it's a click event of a div element Commented Jan 23, 2023 at 20:17
  • Please show us that code. Commented Jan 23, 2023 at 20:17
  • i just added it Commented Jan 23, 2023 at 20:21

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

It worked!! Thanks! But why was my way wrong?
You didn't have the (todo === item) condition I presume. This is limiting the number of renders to 1: When todo === item

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.