Skip to content

Instantly share code, notes, and snippets.

@simicd
Created August 16, 2020 18:20
Show Gist options
  • Save simicd/219be594b9e3f77b049d5f86e44dce6a to your computer and use it in GitHub Desktop.
Save simicd/219be594b9e3f77b049d5f86e44dce6a to your computer and use it in GitHub Desktop.
// useFetch.ts
import { useState, useEffect } from "react";
interface RequestProps {
url: RequestInfo;
init?: RequestInit;
}
type DogImageType = { message: string; status: string };
export const useFetch = ({ url, init }: RequestProps) => {
// Response state
const [data, setData] = useState<DogImageType>();
useEffect(async () => {
try {
// Fetch data from REST API
const response = await fetch(url, init);
if (response.status === 200) {
// Extract json
const rawData: DogImageType = await response.json();
setData(rawData);
} else {
console.error(`Error ${response.status} ${response.statusText}`);
}
} catch (error) {
console.error(`Error ${error}`);
}
}, []);
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment