Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda