samar2170
samar2170

Reputation: 65

Search Function unresponsive in React

I am building a search function at the front end using the filter function, it is not throwing any errors, but is unresponsive, i enter the word in the searchbar and press enter and nothing works. From server logs i can tell on pressing enter it is not making a request to the API. Below is my code:

function Search() {
  const [data, setData] = React.useState([]);
  const [searchTerm, setSearchTerm] = React.useState("");
  const [searchResults, setSearchResults] = React.useState([]);
  const handleChange = e => {
    setSearchTerm(e.target.value);
  };
  const getData = () => {
    axios.get("http://localhost:8000/CBView")
         .then(res => (setData(res.data)))
  }
  React.useEffect(() => {
    const results = data.filter(item =>
      item.toLowerCase().includes(searchTerm)
    );
    setSearchResults(results);
  }, [searchTerm]);
  return (
    <div className="App">
      <input
        type="text"
        placeholder="Search"
        value={searchTerm}
        onChange={handleChange}
      />
      <ul>
        {searchResults.map(item => (
          <li>{item}</li>
        ))}
      </ul>
    </div>
  );
}
export default Search;

Upvotes: 0

Views: 92

Answers (2)

Erick
Erick

Reputation: 1146

Looking at the code , I can see that you need to call the API when the searchTerm changes Please look at the code below

import React from "react";

function Search() {
  const [data, setData] = React.useState([]);
  const [searchTerm, setSearchTerm] = React.useState("");
  const [searchResults, setSearchResults] = React.useState([]);
  const handleChange = e => {
    setSearchTerm(e.target.value);
  };
  const getData = () => {
    axios.get("http://localhost:8000/CBView").then(res => setData(res.data));
  };
  React.useEffect(() => {
    if (searchTerm) {
      getData();
    }
  }, [searchTerm]);

  React.useEffect(() => {
    if(data){
        const results = data.filter(item =>
            item.toLowerCase().includes(searchTerm)
        );
        setSearchResults(results); 
    }
  }, [data]);
  return (
    <div className="App">
      <input
        type="text"
        placeholder="Search"
        value={searchTerm}
        onChange={handleChange}
      />
      <ul>
        {searchResults.map(item => (
          <li>{item}</li>
        ))}
      </ul>
    </div>
  );
}
export default Search;

Upvotes: 1

user14361391
user14361391

Reputation:

Try fixing this part and see if it works,

React.useEffect(() => {
    const results = data.filter(item =>
      item.toLowerCase().search(searchTerm.toLowerCase()) !== -1
    );
    setSearchResults(results);
  }, [searchTerm]);

Upvotes: 0

Related Questions