Create a custom hook to fetch the games

This commit is contained in:
Mosh Hamedani 2023-02-28 11:29:37 -08:00
parent ad1245b94f
commit 2de0630e57
2 changed files with 38 additions and 21 deletions

View file

@ -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<Game[]>([]);
const [error, setError] = useState("");
useEffect(() => {
apiClient
.get<FetchGamesResponse>("/xgames")
.then((res) => setGames(res.data.results))
.catch((err) => setError(err.message));
});
const {games, error} = useGames();
return (
<>

36
src/hooks/useGames.ts Normal file
View file

@ -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<Game[]>([]);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
apiClient
.get<FetchGamesResponse>("/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;