I’ve heard a lot about immutable vs mutable objects when looking at resources for React. However, I’m still a bit confused. In two of my components I have an array, yet updating them the same way creates a bug with one, but not the other. Here’s the arrays in question:
// works fine
const addCategory = () => {
const newCategory = {
name: categoryName,
description: categoryDescription,
};
newPost.setCategories([...newPost.categories, newCategory]);
};
// works fine for the first time, but then adds two objects to the array each time after
const addGroup = () => {
const newGroup = {
name: groupName,
description: groupDescription,
};
newPost.setGroups([...newPost.setGroups, newGroup]);
};
In both cases newPost
is a context and the properties of newCategory
and newGroup
are being set to states that are within their respective components, and then those objects are being pushed to an array in the global context. When I changed addGroup
to
const addGroup = () => {
const newGroup = {
name: groupName,
description: groupDescription,
};
const copy = [...newPost.groups];
copy.push(newGroup);
newPost.setGroups(copy);
};
It now works as it should. I’m not sure if this has to do with me mutating a state incorrectly, but I’m confused as to why it works in one component and doesn’t work in the other.
Is there anything that stands out as a reason this bug could have come up?