Reputation: 1517
I have an array of objects that is like:
const FirstAidTypeSource = [
{ Name: "First Aid", Value: "First Aid" },
{ Name: "Senior First Aid", Value: "Senior First Aid" },
{ Name: "Anaphylaxis Certificate", Value: "Anaphylaxis Certificate" },
{ Name: "Asthma Certificate", Value: "Asthma Certificate" }
];
and every time I use one of them I want it to be removed from the list, for example, if I create the first certificate and select "First Aid" then when I create the second certificate I don't want "First Aid" again in the list and it shouldn't be selectable, even though I found another way to do it which is working ok, but when I delete one certificate everything will mess up, for example, if I add 3 certificates and choose "First Aid" for the first one and "Senior First Aid" for the second one and so on, and then if I want to delete the first one then even though I deleted the first one which is "First Aid" and should be deleted but it is still there and also the "Add Certificate" button will disappear. please refer to the demo for details
any help is appreciated in advance
Upvotes: 0
Views: 82
Reputation: 3178
It's because the button renders if index + 1 === formRef.current
, but formRef.current
isn't being updated when you delete a certificate.
So what I did was change formRef
from a reference to a state, after making sure it's not being used a reference elsewhere. Then set up an effect hook that updates formRef
based on the length of firstAids
each time firstAids
updates.
useEffect(()=>{
setFormRef(firstAids.length)
}, [firstAids])
By having it as a state, the component will re-render after it's updated, and properly render the button.
Try it out:
Upvotes: 1