Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React state changing unexpectedly when trying to dynamically change state

I have certain routes defined in routes.tsx.
I am using this to dynamically populate a sidebar (Material UI Drawer).
The routes have the following structure:

const AppRoutes = {
  group_a: {
    title: "",
    icon: <material icon JSX>,
    path: "",
    children: {
      ...same structure as a group, but without further children
    }
  }
}

After getting the routes, I created a state object to keep track of expanding/collapsing the groups.

let menuGroups = Object.keys(AppRoutes);
const [groupOpen, setGroupOpen] = React.useState(() => {
    const state = {};
    for (let group of menuGroups)
        (state as any)[group] = true;
    return state;
});

const handleGroupToggle = (group: string) => {
    setGroupOpen(state => (state as any)[group] = !(state as any)[group]); // something wrong here? idk
};

But this isn’t working as expected.
Initially the groups are open as expected. But on clicking any group, all groups collapse together. And then another attempt to re-open them results in an error.
Uncaught TypeError: Cannot create property 'group_a' on boolean 'false'
On further investigation, I found that the state object has somehow become just a boolean false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s a codesandbox to replicate this: https://codesandbox.io/s/flamboyant-rgb-oin62u?file=/src/App.js

>Solution :

Two problems:

  1. The callback is not returning the updated state
  2. state is mutated

Fixed handler:

const handleGroupToggle = (group) => {
  setGroupOpen((state) => ({ ...state, [group]: !state[group] }));
};

Edit silly-snyder-el445g

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading