2

Right now my search function is I have to click the search icon to make it appear the result so I want to change that to real-time search. When I type the name in input it will auto-starting appear the user card for me

Here is my following code:

const [searchQuery, setSearchQuery] = 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]);
    setShowInvitees(!showInvitees);
  };
  useEffect(() => {
    if (searchQuery === "") {
      setInvitees([]);
    }
  }, [searchQuery]);

        <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="text"
              name="name"
              onChange={handleChange}
              placeholder="Name"
              aria-label="Search bar"
              pattern="^[a-zA-Z0-9 ]+"
              required
            />
          </div>
        </form>

How can I make it auto-populate when my search query length is >= 2 letters?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Nhan Nguyen
  • 355
  • 1
  • 6
  • 24

1 Answers1

0

You can do so with the help of useEffect

Explanation:

  1. I renamed your handleSubmit function to getInvitees
  2. Calling getInvitees function when searchQuery length is more than or equal to 2

Solution

useEffect(() => {
   if(searchQuery === "") {
      setInvitees([]);
   }    
   if((searchQuery||'').length >= 2) {
      getInvitees();
   }    
}, [searchQuery]);

const getInvitees = async () => { // renamed handleSubmit function to getInvitees
   const res = await axios.get(`/api/v1/search/users/invite/${searchQuery}/${teamId}`);
   setInvitees(res.data[0]);
   setShowInvitees(!showInvitees);
};
Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52