I checked some of the threads about this and tried to fix it, but no succes yet.
I have a parent and a child component. In the parent component, I declare a state and pass the function to update this state on to my child component.
function ProfileGallery() {
const [selectedPet, setPet] = useState(null);
const [filterText, setFilterText] = useState('');
const [pets, setPets] = useState([]);
const [componentState, setState] = useState('test');
const updateState = (state) => {
setState(...state);
};
return (
<PetInformation
selectedPet={selectedPet}
componentState={componentState}
triggerParentUpdate={updateState}
/>
);
}
In my child component, I do the following:
function PetInformation({ componentState, triggerParentUpdate, ...props }) {
const [status, setStatus] = useState('Delete succesful');
const { selectedPet } = { ...props } || {};
const updatedComponentState = 'newState';
useEffect(() => {
if (status === 'Delete pending') {
deletePet(selectedPet).then(() => setStatus('Delete succesful'));
}
}, [status]);
const handleDelete = () => {
setStatus('Delete pending');
};
return (
<button
className="btn btn-primary pull-right"
onClick={() => {
handleDelete();
triggerParentUpdate(updatedComponentState);
}}
type="button"
>
Delete Pet
</button>
There’s of course more code in between, but this shows the gist of what I’m trying to achieve. I want to delete an item I selected in my gallery and have that delete reflected once I click the delete button -> my ProfileGallery needs to re-render. I’m trying to do this by passing that function to update my state on to the child component. I know JS won’t consider state changed if the reference remains the same, so that’s why I am passing a new const updatedComponentState on, since that should have a different reference from my original componentState.
Everything works, the item gets removed but I still need to manually refresh my app before it gets reflected in the list in my gallery. Why won’t ReactJS re-render my ProfileGallery component here? Isn’t my state getting updated?