Home > Software design >  Why are my search bar results not displaying dynamically as I type using React API
Why are my search bar results not displaying dynamically as I type using React API

Time:03-01

I have a search bar which takes the input value and sends it to an API via axios.get(/products/search?q={} ...) and returns a list of possible products.

Technically, the list returned appears as the user types in the search box. This is not working for me.

If I make the app return the search input query, then it displays it letter by letter as expected, but when I try to return a map of the data, it doesn't update the results dynamically, only on reload of the page.

const SearchBar = () => {
  const [data, setData] = useState([]);
  const [query, setQuery] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(`/products/search?q=${query}`);
        console.log(data.results);
        setData(response.data);
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, []);

  const handleFilter = (event) => {
    event.preventDefault();
    const search = event.target.value
      .toLowerCase()
      .normalize("NFD") //.normalize and .replace help by ignoring diacriticals from the data field
      .replace(/[\u0300-\u036f]/g, "");

// HERE IS WHERE I SET THE query FOR THE API
    setQuery(search);
  };

  return (
    // the Search box
    <div className="search">

      <div className="searchInputs">
        <input type="text" placeholder="Search ..." onChange={handleFilter} />
      </div>

      {/* search result suggestions list */}

      {query.length != 0 && (
        <div className="dataResult">
          {data.results.map((product, index) => {
            return (
              <a className="dataItem" key={product._id}>
                {product.name}
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default SearchBar;

A search for Beer: search box


Make any random change to react component and save: data not passed yet


Make another random change and save to the react component all data is passed


Mirroring the input onChange, works dynamically how it should work

CodePudding user response:

Did you try to add query as a dependency to the useEffect?

Like this:

useEffect(() => {}, [query]);

If it will work be careful because every single time user writes any character it will send the request. It would be better to use some bouncing or some sort of way not to run functions immediately, but like 2 seconds after. (SetTimeout maybe)

CodePudding user response:

since you made changes to query, you need to add [query] as a second argument in your useEffect hooks to make the component re-render every time query changes.

  • Related