React onchange event search api onChange is not working properly

Viewed 396

I am searching users in my database with keyword from user. I keep the value in my state and tried to calling the API on onChnge() event but it freezes my input field, I cant' add or remove char from input field it I call API right after onChange(),

I tried the onSubmit it's working as charm, but I want to callt the API on each keystroke.

const CardAddChat = () => {
  const initialState = {
    private: true,
    search: "",
    usersList: [],
    selectedPersons: [],
  };

  const [state, setState] = useState(initialState);

  const handleChange = (e) => {
    setState({ ...state, search: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      let res = await axios.get(`/api/users?term=${state.search}`);
      setState({ ...state, usersList: res.data.data });
    } catch (error) {
      console.error(error);
    }
  };

  const handleGroupChange = () => {
    setState({ ...state, private: !state.private });
  };

  return (
    <>
      <div className=" w-96 flex flex-col bg-blueGray-200 ">
        <h1 className="text-2xl p-3  border-b">
          {state.private ? "New Private Chat" : "New Group Chat"}
        </h1>

        <div className="flex-none  pb-2  ">
          <form
            onSubmit={handleSubmit}
            class="pt-2 relative mx-auto w-full px-2 text-gray-600 flex items-center"
          >
            <input
              class="px-3 bg-white h-10 rounded-full text-xs focus:outline-none w-full pr-10"
              type="search"
              name="search"
              value={state.search}
              onChange={handleChange}
              placeholder="Search for messages or users.."
            />

Here for temporary, I am calling the API onSubmit but any way to make it to trigger at onChange. thanks in advance.

1 Answers

If you've already fetched all of your users, then you only need to filter the list, not fetch a subset of the list already fetched.

If you must fetch the users via the onChange handler, consider using lodash's debounce function - which will wait until typing stops for a brief amount of time before.

Related