diff --git a/src/components/GameGrid.tsx b/src/components/GameGrid.tsx index d6e556d..98407c6 100644 --- a/src/components/GameGrid.tsx +++ b/src/components/GameGrid.tsx @@ -1,27 +1,8 @@ import { Text } from "@chakra-ui/react"; -import React, { useEffect, useState } from "react"; -import apiClient from "../services/api-client"; - -interface Game { - id: number; - name: string; -} - -interface FetchGamesResponse { - count: number; - results: Game[]; -} +import useGames from "../hooks/useGames"; const GameGrid = () => { - const [games, setGames] = useState([]); - const [error, setError] = useState(""); - - useEffect(() => { - apiClient - .get("/xgames") - .then((res) => setGames(res.data.results)) - .catch((err) => setError(err.message)); - }); + const {games, error} = useGames(); return ( <> diff --git a/src/hooks/useGames.ts b/src/hooks/useGames.ts new file mode 100644 index 0000000..6cb129d --- /dev/null +++ b/src/hooks/useGames.ts @@ -0,0 +1,36 @@ +import { CanceledError } from "axios"; +import { useEffect, useState } from "react"; +import apiClient from "../services/api-client"; + +interface Game { + id: number; + name: string; +} + +interface FetchGamesResponse { + count: number; + results: Game[]; +} + +const useGames = () => { + const [games, setGames] = useState([]); + const [error, setError] = useState(""); + + useEffect(() => { + const controller = new AbortController(); + + apiClient + .get("/games", { signal: controller.signal }) + .then((res) => setGames(res.data.results)) + .catch((err) => { + if (err instanceof CanceledError) return; + setError(err.message) + }); + + return () => controller.abort(); + }, []); + + return { games, error }; +} + +export default useGames; \ No newline at end of file