Last active
February 7, 2019 09:43
-
-
Save dagda1/b97b1d6d0d7d0f41eeeeb2fdccccdd5f 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 } 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