Home > Software design >  How to not real time filter
How to not real time filter

Time:11-06

I'm building on my practice web app and I'm tried to filter the data from fetched data but it filter real time. My question is how to make it not real time, like when searchbar is empty it will fetch all data but when type a text in searchbar it will fetch data from input text.

Here is my code

  const { data, loading, error } = useFetch(BASE_URL)
  const [search, setSearch] = useState("")
  const [inp, setInp] = useState("")

  const handleChange = (e) => {
    setSearch(e.target.value)
  }

  if (loading) return <h1> LOADING...</h1>

  if (error) console.log(error)

  return (
    <div className="App" >
      <div className="Container">
        <label className='header'>Topic</label>
        <div className="Container-searchBar">
          <input type="Text" value={search} placeholder="Search . . ." onChange={handleChange}/>
        </div>
        {data.filter((val) => {
          if (search === "") {
            return val
          }
          else if (val.tags.includes(search)) {
            return val
          }
        }).map((post) => {
          return 
.
My return
.

        })}
      </div>
    </div>
  );

I'm new to React and JS so sorry for some bad question.

CodePudding user response:

I did not get what you mean by not real-time filtering. Your approach is okay, if you would like not to apply to filter immediately, you can apply timeout.

const { data, loading, error } = useFetch(BASE_URL);
const [search, setSearch] = useState("");
const [filteredStates, setFilteredStates] = useState([]);

useEffect(() => {
  if (!loading || !search.trim()) {
    setFilteredStates(data);
  } 
const timer = setTimeout(() => {
      const filter = data.filter((val) => {
        return val.tags.toLowerCase().includes(search.toLowerCase());
      });

      setFilteredStates(filter);
    }, 1000);

    return () => clearTimeout(timer);

}, [search, loading]);

const handleChange = (e) => {
  setSearch(e.target.value);
};

if (loading) return <h1> LOADING...</h1>;

if (error) console.log(error);

return (
  <div className="App">
    <div className="Container">
      <label className="header">Topic</label>
      <div className="Container-searchBar">
        <input
          type="Text"
          value={search}
          placeholder="Search . . ."
          onChange={handleChange}
        />
      </div>
      {filteredStates.map((post) => {
        return;
        <></>;
      })}
    </div>
  </div>
);
  • Related