Last active
December 7, 2018 14:59
-
-
Save zachariahtimothy/0d57752e356ea7b47e124d0ea31a7b68 to your computer and use it in GitHub Desktop.
Rest API React hook
This file contains hidden or 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 { useRestAPI } from './hooks/useRestAPI'; | |
export function ComponentWithFetch() { | |
const result = useRestAPI<DataShape>({ url }); | |
const { loading, error, data } = result; | |
if (loading) { | |
return <Loading />; | |
} | |
if (error) { | |
return <Error />; | |
} | |
if (data) { | |
return ( | |
<div> | |
<p>Sweet we have data!</p> | |
{data.sweetArrayOfData.map(item => ( | |
<p key={item.id}>{item.name}</p> | |
))} | |
</div> | |
); | |
} | |
} |
This file contains hidden or 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 fetch from 'isomorphic-unfetch'; | |
import { useEffect, useState } from 'react'; | |
export interface UseRestAPIProps { | |
url: string; | |
} | |
interface Result<DataShape> { | |
data?: DataShape; | |
error?: Error; | |
loading: boolean; | |
} | |
export function useRestAPI<DataShape>(props: UseRestAPIProps) { | |
const { url } = props; | |
const [result, setResult] = useState<Result<DataShape>>({ | |
data: undefined, | |
error: undefined, | |
loading: true, | |
}); | |
useEffect( | |
() => { | |
fetch(url) | |
.then((res: any) => res.json()) | |
.then((resData: any) => setResult({ loading: false, data: resData })) | |
.catch((err: Error) => setResult({ loading: false, error: err })); | |
}, | |
[url] | |
); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment