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