I start with:
constructor() {
super();
this.state = {
lists: [\'Dogs\',\'Cats\'],
items: {Dogs: [{name: \"Snoopy\"}, {name: \"Lola\"
The chosen answer was a miracle and huge props to Nandu Kalidindi, I was having bugs with nested arrays inside of objects that I was updating in my project and was not understanding the concept of "deep" or "nested" arrays and objects not being copied to a new object.
This is my take on his fix and made it look a little more appealing to me and works just as good!
I utilize lodash
and found their _.cloneDeep()
function to serve my updating state needs.
Lodash _.cloneDeep()
I learned that mapping out updated arrays preventing any bugs was the best way to treat that kind of problem, but I was cloning entire objects with nested arrays that were mutating the old object's arrays in the state.
This is my answer.
const state = {
fields: {
"caNyDcSDVb": {
id: "caNyDcSDVb",
name: "test1",
type: "text",
options: ["A", "B", "C"]
}
},
};
const FieldCopy = (id) => {
const newCopiedField = _.cloneDeep(state.fields[id]);
newCopiedField.id = nanoid(10);
return {
...state,
fields: {
...state.fields,
newCopiedField[id]: newCopiedField
}
};
};