Skip to content

Instantly share code, notes, and snippets.

@dagda1
Last active February 7, 2019 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dagda1/b97b1d6d0d7d0f41eeeeb2fdccccdd5f to your computer and use it in GitHub Desktop.
Save dagda1/b97b1d6d0d7d0f41eeeeb2fdccccdd5f to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
export interface UseFetchData<TData> {
data: TData;
isLoading: boolean;
error?: string;
}
export const useFetchData = <TData>(fetchUrl: string, defaultValue: TData): UseFetchData<TData> => {
const [data, setData] = useState<TData>(defaultValue);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<string | undefined>(undefined);
const fetchData = async () => {
const setErrorMessage = (errorMessage: string) => {
setError(errorMessage);
setIsLoading(false);
};
try {
const result = await fetch(fetchUrl);
if (!result.ok) {
setErrorMessage(result.statusText);
return;
}
setData(await result.json());
setIsLoading(false);
} catch (err) {
setErrorMessage(err.message);
}
};
useEffect(() => {
fetchData();
// tslint:disable-next-line
}, [fetchUrl]);
return { data, isLoading, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment