Last active
June 10, 2020 01:47
-
-
Save claeusdev/c636153796de1da548f0801a40ea83c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useCallback } from "react"; | |
import { server } from "./server"; | |
interface State<TData> { | |
data: TData | null; | |
loading: boolean; | |
error: boolean; | |
} | |
export const useQuery = <TData = any>(query: string) => { | |
const [state, setState] = useState<State<TData>>({ | |
data: null, | |
loading: false, | |
error: false, | |
}); | |
const fetch = useCallback(() => { | |
const fetchApi = async () => { | |
try { | |
setState({ loading: true, data: null, error: false }); | |
const { data, errors } = await server.fetch<TData>({ query }); | |
if (errors && errors.length) { | |
throw new Error(errors[0].message); | |
} | |
setState({ data, loading: false, error: false }); | |
} catch (error) { | |
setState({ data: null, loading: false, error: true }); | |
throw console.error(error); | |
} | |
}; | |
fetchApi(); | |
}, [query]); | |
useEffect(() => { | |
fetch(); | |
}, [fetch]); | |
return { ...state, refetch: fetch }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment