'Set state twice in onChange ReactJS

I have the following snippet of React that I can't get to work right. Essentially I'm displaying a spinner based on the state of this onChange call (due to the update sometimes taking 3-5 seconds). However, the first call to set state seems to go unnoticed (or as I'm researching being batched up) and therefore the state of loading is never updated. This is part of a toggle/switch a user can select infinite times on a page (if they desired obviously).

  const [state, setState] = useState({ loading: false });  
  const onToggleChange = () => {
    setState(prevState => {
      return {
        ...prevState,
        loading: true,
      };
    });
    console.log("loading1: " + JSON.stringify(state));

    // this takes a long time depending on the users actions
    setFilterMode(!filterChecked);

    setState(prevState => {
      return {
        ...prevState,
        loading: false,
      };
    });
    console.log("loading2: " + JSON.stringify(state));
  };

I've reviewed the current questions/answer (which is how I got as far as the above), but it still doesn't load correctly.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source