Created
May 25, 2020 13:05
-
-
Save ralfting/9ee856c4c82e4a3f06c37af7e18ecc90 to your computer and use it in GitHub Desktop.
Snippet to use custom hook inspired by react-query "useQuery"
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 { useEffect, useState, useCallback } from 'react'; | |
import { ApiSuccessfulResponse } from 'types/api'; | |
export default function useQuery<T>( | |
query: (params: string) => Promise<ApiSuccessfulResponse<T>>, | |
params: string | |
) { | |
const [isLoading, setLoading] = useState(true); | |
const [data, setData] = useState<T>(); | |
const [error, setError] = useState(); | |
const request = useCallback( | |
async function request() { | |
try { | |
setLoading(true); | |
const response = await query(params); | |
setData(response.data); | |
setLoading(false); | |
} catch (error) { | |
setError(error); | |
setLoading(false); | |
console.error(error); | |
} | |
}, | |
[query, params] | |
); | |
useEffect(() => { | |
request(); | |
}, [request]); | |
return { isLoading, data, error, refetch: request }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment