diff --git a/src/components/Image/Image.tsx b/src/components/Image/Image.tsx new file mode 100644 index 0000000..3177634 --- /dev/null +++ b/src/components/Image/Image.tsx @@ -0,0 +1,43 @@ +import { useEffect, useState } from 'react'; + +import { createClient } from 'pexels'; +import type { ErrorResponse, Photo } from 'pexels'; +import { FruitType } from 'src/types'; + +interface ImageProps { + item: FruitType; +} + +function Image({ item }: ImageProps) { + const client = createClient(process.env.REACT_APP_PEXEL_API_KEY as string); + const [photo, setPhoto] = useState(null); + + const fetchImage = (query: string) => { + client.photos + .search({ query, per_page: 1 }) + .then((data) => { + if (!('error' in data)) { + setPhoto(data.photos[0]); + } + }) + .catch((error: ErrorResponse) => { + throw new Error(error.error); + }); + }; + + useEffect(() => { + fetchImage(item.name); + }, []); + + return ( +
+ {photo?.alt +
+ ); +} + +export default Image; diff --git a/src/components/Image/index.ts b/src/components/Image/index.ts new file mode 100644 index 0000000..5f57d67 --- /dev/null +++ b/src/components/Image/index.ts @@ -0,0 +1 @@ +export { default } from './Image'; diff --git a/src/components/Products/Products.tsx b/src/components/Products/Products.tsx new file mode 100644 index 0000000..5417b61 --- /dev/null +++ b/src/components/Products/Products.tsx @@ -0,0 +1,46 @@ +import { useEffect, useState } from 'react'; + +import Image from 'src/components/Image'; +import PaginationControls from 'src/components/PaginationControls'; +import usePagination from 'src/hooks/usePagination'; +import { FruitType } from 'src/types'; + +function Products() { + const [fruits, setFruits] = useState(null); + const { currentPage, getCurrentData, setCurrentPage, pageCount } = usePagination(fruits || [], 5); + + const fetchFruitsData = async () => { + try { + const url = 'https://proxyserver-phi.vercel.app/'; + const res = await fetch(url); + const fruits = await res.json(); + + setFruits(fruits); + } catch (error: unknown) { + if (typeof error == 'string') { + throw new Error(error); + } else { + console.error(error); + } + } + }; + + useEffect(() => { + fetchFruitsData(); + }, []); + + if (!fruits) return

Loading...

; + + return ( +
+
+ {getCurrentData().map((item) => { + return ; + })} +
+ +
+ ); +} + +export default Products; diff --git a/src/components/Products/index.ts b/src/components/Products/index.ts new file mode 100644 index 0000000..4a40fee --- /dev/null +++ b/src/components/Products/index.ts @@ -0,0 +1 @@ +export { default } from './Products';