Skip to content

Instantly share code, notes, and snippets.

@ralfting
Created May 25, 2020 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralfting/9ee856c4c82e4a3f06c37af7e18ecc90 to your computer and use it in GitHub Desktop.
Save ralfting/9ee856c4c82e4a3f06c37af7e18ecc90 to your computer and use it in GitHub Desktop.
Snippet to use custom hook inspired by react-query "useQuery"
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