0

Probably it is a classic issue with useState which is not updating.

So there is a tree with some checkboxes, some of them are already checked as they map some data from an endpoint.

The user has the possibility to check/uncheck them. There is a "cancel" button that should reset them to the original form.

Here is the code:

  const [originalValues, setOriginalValues] = useState<string[]>([]);

  ...

  const handleCancel = () => {
    const originalValues = myData || []; //myData is the original data stored in a const
    setOriginalValues(() => [...myData]);
  };

  ...

  useEffect(() => {
    setOriginalValues(originalValues);
  }, [originalValues]);

However, it is not working, the tree is not updating as it should. Is it something wrong here?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • 1
    The first issue I see is that you're running into some kind of infinite loop with `useEffect(() => { setOriginalValues(originalValues); }, [originalValues]);`. Remove originalValues from the dependency array to get out of the loop. Please provide a condesandbox demonstrating your issue. – Moath Jul 19 '22 at 13:47
  • What is not working? Checking/unchecking individual checkboxes? Or resetting – Ladmerc Jul 19 '22 at 13:51
  • Also, the handler is probably not doing what you intend. What do you _think_ is happening in there? – Matt Morgan Jul 19 '22 at 13:52

1 Answers1

0

Just do the following, no need for ()=> the state will update inside the hook if called, plus change the constant it will cause confusion inside your code and protentional name clash later on, with the current state variable name, and also make sure your data are there and you are not injection empty array !!!! which could be the case as well !.

// Make sure data are available
console.log(myData)
// Then change the state
setOriginalValues([...myData]);
Richardson
  • 1,804
  • 10
  • 38