diff --git a/src/App.tsx b/src/App.tsx index fc3c47c..7862e0f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react' +import { useFetch } from './hooks/useFetch' type Repository = { id: string; @@ -7,20 +7,14 @@ type Repository = { } function App() { - const [repositories, setRepositories] = useState([]) - - useEffect(() => { - fetch("https://api.github.com/users/AdrianeRibeiro/repos") - .then(response => response.json()) - .then(data => { - setRepositories(data) - }) - }, []) + const { data: repositories, isFetching } + = useFetch("/users/AdrianeRibeiro/repos") return ( -
+ <>
    - {repositories && repositories.map(repo => { + { isFetching &&

    Carregando

    } + {repositories?.map(repo => { return(
  • {repo.full_name} @@ -29,7 +23,7 @@ function App() { ) })}
-
+ ) } diff --git a/src/hooks/useFetch.ts b/src/hooks/useFetch.ts new file mode 100644 index 0000000..db207fb --- /dev/null +++ b/src/hooks/useFetch.ts @@ -0,0 +1,29 @@ +import { useState, useEffect } from 'react' +import axios, { AxiosRequestConfig } from 'axios' + +const api = axios.create({ + baseURL: 'https://api.github.com' +}) + +//T é genérico +export function useFetch(url: string, options?: AxiosRequestConfig) { + const [data, setData] = useState(null) + const [isFetching, SetIsFetching] = useState(true) + const [error, setError] = useState(null) + + useEffect(() => { + api.get(url) + .then(response => { + setData(response.data) + }) + .catch(err => { + setError(err) + }) + .finally(() => { + SetIsFetching(false) + }) + }, []) + + return { data, error, isFetching } +} +