Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda