Skip to content

Instantly share code, notes, and snippets.

@borakasmer
Last active March 30, 2022 13:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borakasmer/eb515e3f0f943c211f884a7e983b4586 to your computer and use it in GitHub Desktop.
Save borakasmer/eb515e3f0f943c211f884a7e983b4586 to your computer and use it in GitHub Desktop.
React Search TODO
import React, {useCallback, useEffect, useState} from "react";
let MY_LIST = [];
let RealData = [];
function App() {
const [search, setSearch] = useState("");
const [filterlist, setFilterlist] = useState(MY_LIST);
//Debounce Time
const debounce = (func) => {
let timer;
return function (...args) {
const context = this;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
func.apply(context, args);
}, 500);
};
};
const optimizedFn = useCallback(debounce(onKeyUpHandler), []);
//-----------------------------
function searchData() {
console.log("Search: " + search);
/*MY_LIST=[];
RealData.forEach(element => {
if(element.title.includes(search)){
MY_LIST.push(element);
}
}); */
MY_LIST = RealData.filter((e) => e.title.includes(search))
setFilterlist(MY_LIST);
}
function fetchData() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((response) => response.json())
.then((data) => {
MY_LIST = data;
RealData = data;
setFilterlist(MY_LIST);
});
}
function onKeyUpHandler(e) {
setSearch(e.target.value.toLowerCase());
}
useEffect(() => {
console.log("executed only Once!!");
fetchData();
}, []);
useEffect(() => {
console.log("executed only search change!");
searchData();
}, [search]);
return (
<div className="container mt-5">
<input
id="searchFilter"
type="text"
className="form-control"
defaultValue={search}
placeholder="Enter ID or Name"
onKeyUp={optimizedFn}
//onKeyUp={onKeyUpHandler}
/>
<ul className="list-group">
{filterlist.map((item, key) => (
<li className="list-group-item" key={key} value={item.id}>
{item.id}) {item.title}
</li>
))}
</ul>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment