Skip to content

Instantly share code, notes, and snippets.

@zachariahtimothy
Last active December 7, 2018 14:59
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 zachariahtimothy/0d57752e356ea7b47e124d0ea31a7b68 to your computer and use it in GitHub Desktop.
Save zachariahtimothy/0d57752e356ea7b47e124d0ea31a7b68 to your computer and use it in GitHub Desktop.
Rest API React hook
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>
);
}
}
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