From d542415c4a5eeb0d0e8003389ea126eca9973c36 Mon Sep 17 00:00:00 2001 From: Dung Le Date: Sat, 5 Oct 2024 22:44:21 +0700 Subject: [PATCH] Add search function --- src/components/Input/index.tsx | 77 ++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx index 453c742..4aeb0e3 100644 --- a/src/components/Input/index.tsx +++ b/src/components/Input/index.tsx @@ -2,6 +2,7 @@ import "./input.scss"; import { fetchData } from "../../utils/fetch-data"; import { debounce } from "../../utils/deboucne"; import Loader from "../Loader"; +import { useEffect, useState } from "react"; export interface InputProps { /** Placeholder of the input */ @@ -12,12 +13,82 @@ export interface InputProps { const Input = ({ placeholder, onSelectItem }: InputProps) => { // DO NOT remove this log - console.log('input re-render') + console.log("input re-render"); // Your code start here - return + const [result, setResult] = useState([]); + const [errorMessage, setErrorMessage] = useState(""); + + const [searchString, setSearchString] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const [isEmptySearch, setIsEmptySearch] = useState(true); + + const handleInputChange = debounce((value: string) => { + if (!value) { + setIsEmptySearch(true); + setErrorMessage(""); + setSearchString(""); + return; + } + setIsLoading(true); + setSearchString(value); + }, 100); + + useEffect(() => { + if (!searchString) return; + let skip = false; + fetchData(searchString) + .then((data) => { + if (skip) return; + setErrorMessage(""); + setResult(data); + setIsEmptySearch(false); + }) + .catch((error) => { + if (skip) return; + setErrorMessage(error); + setIsEmptySearch(false); + setResult([]); + }) + .finally(() => { + setIsLoading(false); + }); + + return () => { + skip = true; + }; + }, [searchString]); + + const resultRender = () => { + if (isLoading) return ; + + if (errorMessage) return
{errorMessage}
; + + if (result && result.length) { + return ( + + ); + } + + if (result && !result.length) return
No item found!
; + }; + + return ( + <> + handleInputChange(e.target.value)} + > + {!isEmptySearch && resultRender()} + + ); // Your code end here }; export default Input; -