I am trying to create a button undo when the User hits the invite button to invite another user into the team and it the invitation will take 10s and then send the invite to that user meanwhile make the undo button appear and in 10s user can undo the invitation.
How can I use useDebounce in this case?
Here is my following code:
import { useDebounce } from "use-debounce";
const InviteCard = (props) => {
const {
user,
tab,
teamId,
privateTeamId,
onSubmiteInvitee,
isInvitationAvailable,
searchQuery,
invite,
} = props;
async function inviteToTeam(e) {
if (!user.verifiedDT) {
notify("User has not verified their identity, can not invite.");
} else {
const res = await axios.post("/api/v1/invites/invite", {
userToInvite: user.public_user_id,
teamId: teamId,
});
if (res.data.inviteWasCreated === false) {
notify("User has already been invited.");
} else if (res.data.error !== undefined) {
notify(res.data.error);
} else if (res.data.msg) {
if (res.data.msg === "max members") {
toggleRequestModal();
setLimitType("team members");
}
if (res.data.msg === "max invites") {
toggleRequestModal();
setLimitType("invites");
}
} else {
notify("Invite sent.");
setWhatToReload("invite data");
onSubmiteInvitee(e);
}
}
}
const handleSubmitInvite = (e) => {
e.preventDefault();
inviteToTeam(e);
};
let debounceInvite = useDebounce(inviteToTeam, 500);
useEffect(() => {
}, [debounceInvite]);
return (
<div ref={domNode}>
<form onSubmit={handleSubmitInvite}>
<button type="submit" className="invitees-invite-button">
Invite
</button>
</form>
</div>
);
};
export default InviteCard;
Update. add new function:
const [sent, setSent] = useState(false);
const [timeoutId, setTimeoutId] = useState();
const handleSubmitInvite = (e) => {
e.preventDefault();
// call "inviteToTeam" function after 10s
const id = setTimeout(() => {
inviteToTeam(e);
}, 10 * 1000);
setSent(!sent);
// save the timer id in the state
setTimeoutId(id);
};
const onUndoClick = (timeoutId) => {
// get the timeout id from the state
// and cancel the timeout
setSent(false);
clearTimeout(timeoutId);
};
{!sent &&
!isInvitationAvailable(privateTeamId, user.InvitesApplications) && (
<div>
<form onSubmit={handleSubmitInvite}>
<button type="submit" className="invitees-invite-button">
Invite
</button>
</form>
</div>
)}
{sent && <button onClick={onUndoClick}>Undo</button>}