Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
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.

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!