0

I am trying to achieve that after I click handle submit the setInvitees(res.data) will update new data.

My project is when I search a list of user and hit invite button it will auto update my user status to pending. When hit invite button in InviteCard component it need to update the setInvitees(res.data) and how can I do that in this case? Or is there any way I can update the setInvitees after hit inviteToTeam function

Here is my following code for Invitees.js component:

const Invitees = (props) => {
  const { tab, teamId, privateTeamId, fetchTeamData } = props;
  const [searchQuery, setSearchQuery] = useState("");
  const [invitees, setInvitees] = useState([]);

  const handleChange = (event) => {
    event.preventDefault();
    setSearchQuery(event.target.value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await axios.get(
      `/api/v1/search/users/invite/${searchQuery}/${teamId}`
    );
    setInvitees(res.data[0]);
  };

  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }
  }, [searchQuery]);

  console.log(invitees);

  return (
    <div className="invitees-container">
      <div className="invitees-wrapper">
        <div className="invitees-sortes">
          Sort by: <u>Recommended</u>{" "}
          <svg
            width="12"
            height="6"
            viewBox="0 0 12 6"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path d="M6 6L0.803848 0L11.1962 0L6 6Z" fill="#A9A9A9" />
          </svg>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="invitees-search">
            <Button
              className="input invitees--search-icon"
              style={{ color: "white", backgroundColor: "#00B790" }}
              type="submit"
            >
              <SearchIcon />
            </Button>
            <input
              className="invitees--search_input"
              type="search"
              name="name"
              onChange={handleChange}
              placeholder="Name, Skill, Location"
              aria-label="Search bar"
              pattern="^[a-zA-Z0-9 ]+"
              required
            />
          </div>
        </form>
      </div>
      <Grid
        container
        direction="row"
        justify="flex-start"
        alignItems="stretch"
        spacing={7}
      >
        {invitees
          .filter(
            (userTeamId) =>
              userTeamId.Memberships.length < 1 ||
              userTeamId.Memberships.every(
                (member) => member.teamId !== privateTeamId
              )
          )
          .map((user, index) => (
            <Grid item key={index}>
              <div className="member-card">
                {user.InvitesApplications.map((ures, index) => (
                  <div key={index}>
                    {ures.response === "Waiting on response" && (
                      <div className="member-card-header pending">Pending</div>
                    )}
                    {ures.response === "Declined" && (
                      <div className="member-card-header declined">
                        Declined
                      </div>
                    )}
                  </div>
                ))}
                <div>
                  <InviteCard tab={tab} user={user} teamId={teamId} />
                  {user.InvitesApplications.map((ures, index) => (
                    <div>
                      {ures.response === "Declined" && (
                        <div className="declined-status">
                          Declined on{" "}
                          {moment(ures.updatedAt).format("MMMM DD, YYYY")}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </Grid>
          ))}
      </Grid>
      {invitees.length > 0 && (
        <div className="invitees-email-invitation">
          <span>Can't find someone?</span>
          <button>Invite via Email</button>
        </div>
      )}
    </div>
  );
};

and here is my InviteCard.js component:

const InviteCard = (props) => {
  const { user, tab, teamId } = props;
  const [modalStatus, setModalStatus] = useState(false);
  const [limitType, setLimitType] = useState("team members");
  const appState = useContext(GlobalContext);
  const { setWhatToReload } = appState;

  const openModal = () => {
    setModalStatus(!modalStatus);
  };

  const notify = (message) =>
    toast.info(<CustomToastMessage message={message} />, {
      autoClose: 2000,
      closeButton: true,
      hideProgressBar: false,
      transition: Flip,
      position: "bottom-right",
    });

  async function inviteToTeam() {
    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");
      }
    }
  }

  const handleSubmitInvite = (e) => {
    e.preventDefault();
    inviteToTeam();
  };

  return (
    <div className="invite-card-body">
      <div className="member-edit" onClick={openModal}>
        <Symlink />
      </div>
      {modalStatus && <TeamStatusModal active={modalStatus} tab={tab} />}
      <div
        className="member-avatar"
        style={{
          backgroundImage: `url(${user.picture})`,
        }}
      />
      <div className="member-description">
        <p className="member-name">{user.fullname}</p>
        <p className="member-position">{user.major}</p>
      </div>
      {user.InvitesApplications.length < 1 ? (
        <form onSubmit={handleSubmitInvite}>
          <button type="submit" className="invitees-invite-button">
            Invite
          </button>
        </form>
      ) : (
        ""
      )}
    </div>
  );
};
1
  • Anyone know how I can implement this? Commented May 8, 2021 at 9:38

1 Answer 1

1

This is the first time I'm trying to answer a question.

You can send your handleSubmit function to the InviteCard component on Invitees.js as props:

<InviteCard tab={tab} user={user} teamId={teamId} onSubmitInvitee={handleSubmit} />

Then on InviteCard.js use it whenever you need it after destructuring it with the rest of your props. Perhaps inside the inviteToTeam function at the last else statement:

  } else {
    notify("Invite sent.");
    setWhatToReload("invite data");
    onSubmitInvitee();
  }
Sign up to request clarification or add additional context in comments.

4 Comments

I really appreciate it. After tried your code i am getting error TypeError: Cannot read property 'preventDefault' of undefined at handleSubmit in Invitees.js component
On your <form> tag, have you tried the following <form onSubmit={() => handleSubmitInvite()}>? You should call the function instead of just "passing" it as props.
So I dont need e.preventDefaullt() anymore right?
Great, please notice the difference, while sending as props just the function name you can pass it to the corresponding component (in your case it's just a element <form> and not a component). If you want to invoke the function use () => function() to capture the event and invoke the function. Good luck! e.preventDefault() prevents the default behavior of submitting the form on click, if you still need to cancel this behavior you should use it else you can get rid of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.