My father component FatherComponent holds a useState called objectList that contains a list of objects. testComponents is iterated over to generate a list of child components called ChildComponent. FatherComponent contains a button (addComponent) *that adds an object to objectList when clicked, therefore creating a new ChildComponent. Each ChildComponent holds a ‘removeComponent‘ button that allows the current component to be deleted. This button works correctly in updating the objectList but it doesn’t trigger a re-render of the father component. Only the addComponent button does. Here’s my code:
const FatherComponent = ({data}) => {
const [objectList, setObjectList] = useState(data.objects)
//each element of objectList is assigned an incremental unique id when created,
//the id is used to delete the correct object from objectList
const removeComponent = (id) => {
let newObjectList = objectList
let index = newObjectList.findIndex(object => object.id === id);
newObjectList.splice(index, 1);
setObjectList(newObjectList)
}
const addComponent = (prevObjects) => {
setObjectList([...prevObjects, new Object(data.testCount)])
data.newObjectId += 1
}
useEffect(() => {
data.objects = objectList
}, [objectList, data])
return (
<Fragment>
...
<button onClick={() => addComponent(objectList)}>Add Component</button>
{objectList.map((childComponent) => (
<ChildComponent
object={childComponent}
removeComponent={() => removeComponent(childComponent.id)} />
))}
</Fragment>
}
Keep in mind that it is my interest for the objectList to be part of a big class structure, holding all the information in my tool. That is why you see it updated in useEffect
. that is not the only reason. useState is initialized with the values of data
on every re-render so it has to be updated. Here is the ChildComponent:
const ChildComponent = ({ object, removeComponent }) => {
return (
...
<button onClick={removeComponent}>Remove Component</button>
...
);
}
I don’t understand why the FatherComponent doesn’t re-render when removeComponent
is called. The function contains a useState setter, shouldn’t that trigger a re-render?