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

172
Vistas
How to neatly push an object in another complex object in react state?

I am trying to declare a complex array using react hook as

const [strategy, setStrategy] = useState([leg]);

where

const leg = {
  entry: {
    conditions: [],
    actions: [""],
  },
  exit: {
    conditions: [],
    actions: [""],
  },
};

and

const condition = (param) => {
  return { param, val: "" };
};

Now, the following code to add a leg in the array is working fine

const addLeg = () => {
    const temp_strategy = [...strategy];
    temp_strategy.push(leg);

    setStrategy(temp_strategy);
};

Now, I want to add a condition in one of the legs whose index is given (on a button click in the front-end), following is the code I am trying

  const addCondition = (index, trigger, condition_param) => {
    // index is for leg
    // trigger is either 'entry' or 'exit'

    const temp_strategy = [...strategy];

    temp_strategy[index][trigger]['conditions'].push(condition(condition_param));

    setStrategy(temp_strategy);
  };

Now if at some point strategy is having 3 legs and if I call

addCondition(1, 'entry', 'and')

then it is appending the above condition to all 3 legs but inside the 'entry' object.

My doubt is why it is not working for the index but it is working for the trigger where index and trigger are as

temp_strategy[index][trigger]['conditions'].push(condition(condition_param));
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There is a beautiful library specially built for such a scenario immer.js. Go check this out at https://www.npmjs.com/package/immer

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