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));
There is a beautiful library specially built for such a scenario immer.js. Go check this out at https://www.npmjs.com/package/immer