I created a function that when hit invite button then setInterval will start count down from 10 to 0 and then it will send the invitation to user but after the number hit 0 it still keep counting down but the invitation was sent.
Here is my following code:
const [sent, setSent] = useState(false);
const [timeoutId, setTimeoutId] = useState(null);
const [count, setCount] = useState(10);
const [intervalval, setIntervalval] = useState();
const [anchorEl, setAnchorEl] = useState();
const handleSubmitInvite = (e) => {
e.preventDefault();
// call "inviteToTeam" function after 10s
const id = setTimeout(() => {
inviteToTeam(e);
}, 10 * 1000);
const interval = setInterval(() => {
setCount((currentCount) => --currentCount);
}, 1000);
if (interval === 0) {
setSent(false);
}
setIntervalval(interval);
setSent((currentSentValue) => !currentSentValue);
setTimeoutId(id); // save the timer id in the state
};
const onUndoClick = () => {
clearInterval(intervalval);
setCount(10);
setSent((currentSentValue) => !currentSentValue); // get the timeout id from the state and cancel the timeout
clearTimeout(timeoutId);
};
{!sent &&
!isInvitationAvailable(privateTeamId, user.InvitesApplications) &&
user.verifiedDT !== null && (
<div>
<form onSubmit={handleSubmitInvite}>
<Button type="submit" className={classes.inviteButton}>
Invite
</Button>
</form>
</div>
)}
{sent && (
<Button className={classes.unInviteButton} onClick={onUndoClick}>
Uninvite {count}
</Button>
)}