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

155
Vistas
How to update nested object state in React

I have multiple checkbox svgs which i'm mapping over which removes the inner tick icon when I manually set either of the isSelected states to false. I want to remove/add the tick icon svg when I press the checkbox in my app. Im unsure where Im currently going wrong in my logic. It works correctly when I manually change the isSelected state to false but not when I press the checkbox.

State:

  const [option, setOption] = useState([
    { permission: 'Can manage users', isSelected: true },
    { permission: 'Can place orders', isSelected: true },
  ]);

Component:

      {option.map(({ permission, isSelected }, i) => (
          <CheckboxIcon
            viewed={isSelected}
            onPress={() =>
              setOption(prev => {
                prev[i] = { ...prev[i], isSelected: !isSelected };
                return prev;
              })
            }
          />

Checkbox svg:

const CheckboxIcon = ({
  width = 26,
  height = 26,
  viewed,
  fill = Colors.success,
  tickAccountSize,
  onPress,
}) => (
    <Svg
      xmlns="http://www.w3.org/2000/svg"
      overflow="visible"
      preserveAspectRatio="none"
      width={width}
      height={height}>
      <Path
        d="M1 1h24v24H1V1z"
        vectorEffect="non-scaling-stroke"
        fill="transparent"
      />
      <IconContainer onPress={onPress} width={width} height={height}>
        {viewed && <TickIcon tickAccountSize fill={fill} />}
      </IconContainer>
    </Svg>
);
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You have to update the complete object. Your approach is to modify the object.

AFAIK React useState do not track nested objects (also arrays). This will be triggered by replacing the state.

In your case for example:

      {option.map(({ permission, isSelected }, i) => (
      <CheckboxIcon
        viewed={isSelected}
        onPress={() =>
          setOption(prev => prev.splice(i, 1,  {
                    ...prev[i],
                    isSelected: !isSelected
                 })
        }
      />

With splice we insert at index i, remove 1 item (the old one) and insert the new object. Afterwards a new array is returned

In this case with splice we would hold the position and update the specified element.

Also here has someone write a good explanation https://stackoverflow.com/a/43041334/19600120

about 4 years ago · Santiago Trujillo Denunciar

0

In the setOptions functions you are returning the same state. Also mutating the state which is not good. You can change it like below.

 setOption(option => {
                newOption = [...option];
                newOption[i] =  !newOption[i].isSelected ;
                return newOption;
              })

I haven't tested this locally but conceptually will look like this. You can create it in codesandbox then I can fix it for you.

about 4 years ago · Santiago Trujillo Denunciar

0

You should consider to use Immutability Helpers for best performance https://reactjs.org/docs/update.html

Example:

import update from 'react-addons-update';

const newData = update(myData, {
  x: {y: {z: {$set: 7}}},
  a: {b: {$push: [9]}}
});
about 4 years ago · Santiago Trujillo 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