简体   繁体   中英

How can I create a count down number for setTimeout in react

I am trying to create count down number for undo button.

For example: when the User hits the invite button to invite another user into the team and the invitation will count down from 10 to 0 and then send the invite if not click to undo button.

Here is my following code:

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 [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>}

How can I achieve this feature? Do I need to use lodash??

I think the problem is in function onUndoClick . You have a state with name timeoutId , but the onUndoClick function accepts a parameter with the same name, so it uses value of the parameter, and you never use actual state value and never cancel the timeout.Try with:

// parameter removed
const onUndoClick = () => {
    // get the timeout id from the state
    // and cancel the timeout
    setSent(false);
    clearTimeout(timeoutId);
  };
 const [count, setCount] = useState(10);

 const handleSubmitInvite = () => {
    const interval = setInterval(() => {
      setCount((currentCount) => --currentCount);
    }, 1000);
    //execute your function
    if (count === 0) {your fuction};

    // cleanup
    return () => clearInterval(interval);
 }

 const onUndoClick = () => {
   setSent(false);
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM