mirror of
https://github.com/mosh-hamedani/game-hub.git
synced 2026-05-21 12:14:32 +02:00
Create a custom hook to fetch the games
This commit is contained in:
parent
ad1245b94f
commit
2de0630e57
|
|
@ -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
36
src/hooks/useGames.ts
Normal 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;
|
||||
Loading…
Reference in a new issue