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

178
Views
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 answers
Answer question

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 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!