1

I've tried quite a few methods but I have not been able to get onChange to update the userSearchSuggestion state. I'm working on a search-bar component that makes a fetch call after the user has not changed the search bar input for 3 seconds, but it appears that onChange is not firing at all when text is added to the component. Here is the code:

    import React, { useState, useEffect } from "react";
import Select from "react-select";

export default function SearchBar() {
  const [userSearchInput, setUserSearchInput] = useState("");
  const [searchSuggestions, setSearchSuggestions] = useState([]);


  useEffect(() => {
    const searchSuggestions = async (searchInput) => {
      console.log("api called");
      const searchSuggestions = await fetch(
        "API STUFF"
      )
        .then((response) => response.json())
        .then((data) => {
          setSearchSuggestions(data.quotes);
        });
    };

    const timer = setTimeout(() => {
      if (userSearchInput !== "") {
        searchSuggestions(userSearchInput);
      }
    }, 3000);
    return () => clearTimeout(timer);
  }, [userSearchInput]);

  return (
    <Select
      value={userSearchInput}
      options={searchSuggestions}
      onChange={(e) => setUserSearchInput(e.currentTarget.value)}
      placeholder="Search a ticker"
    />
  );
}

Any ideas on why onChange is not updating the state? Even if I simply console.log(e) on onChange, nothing is logged into the console.

1 Answers1

1

If you want to call the API when the user types in the Select input, use onInputChange instead of onChange.

  • Use onChange when you want to execute some code when the user selects something.
  • Use onInputChange when you want to execute some code when the user types something.
<Select onInputChange={(input) => console.log(input)}

I also see you want to delay the API calls a bit when the user is typing. It's a good practice, but the conventional way to do that is to use debounce or throttle. You can see the different between them here.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230