⚒️ Fix search.

This commit is contained in:
pheralb 2022-06-28 18:39:09 +01:00
parent f1e0ea48f0
commit 29da05b302

View File

@ -1,10 +1,8 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { Input, Text, Image, HStack, Box, Center } from "@chakra-ui/react";
import useSWR from "swr";
import useDebounce from "@/hooks/useDebounce";
import { SVGCardProps } from "@/interfaces/components";
import CustomLink from "@/common/link";
import Error from "@/components/error";
import { getSvgByQuery } from "@/services";
import CustomIconBtn from "@/common/iconBtn";
import { Trash } from "phosphor-react";
@ -12,15 +10,24 @@ import Tap from "@/animations/tap";
const Search = () => {
const [search, setSearch] = useState("");
const [results, setResults] = useState<SVGCardProps[]>([]);
const debouncedSearch = useDebounce(search, 500);
const { data, error } = useSWR(`${getSvgByQuery}${debouncedSearch}`);
if (error) {
<Error title="Error" description="an error occurred with your search" />;
}
useEffect(() => {
if (debouncedSearch) {
fetch(getSvgByQuery + debouncedSearch).then((res) => {
if (res.ok) {
res.json().then((data) => {
setResults(data);
});
}
});
}
}, [debouncedSearch]);
const handleClear = () => {
setSearch("");
setResults([]);
};
return (
@ -29,14 +36,14 @@ const Search = () => {
width="full"
variant="flushed"
size="lg"
placeholder="Search"
placeholder="Search svgs..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{data && data.length > 0 && (
{results && results.length > 0 && (
<>
<HStack spacing={4} mt={4} overflowY="hidden">
{data.map((item: SVGCardProps) => (
<HStack spacing={4} mt={4} overflowX="auto" overflowY="hidden">
{results.map((item: SVGCardProps) => (
<Tap key={item.title}>
<CustomLink href={`/svg/${item.id}`}>
<Box
@ -61,11 +68,13 @@ const Search = () => {
</Tap>
))}
</HStack>
<CustomIconBtn
title="clear"
icon={<Trash size={16} />}
onClick={handleClear}
/>
<Box p="3">
<CustomIconBtn
title="clear"
icon={<Trash size={16} />}
onClick={handleClear}
/>
</Box>
</>
)}
</>