简体   繁体   中英

React useState doesn't update even with useEffect added

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM