Skip to content

Instantly share code, notes, and snippets.

@simicd
Last active February 4, 2022 20:40
Show Gist options
  • Save simicd/02ce79612d0971441b33b7c816930d8e to your computer and use it in GitHub Desktop.
Save simicd/02ce79612d0971441b33b7c816930d8e to your computer and use it in GitHub Desktop.
import { useState, useEffect, useCallback } from "react";
interface RequestProps<T> {
url: RequestInfo;
init?: RequestInit;
processData?: (data: any) => T;
}
export const useFetch = <T>({ url, init, processData }: RequestProps<T>) => {
// Response state
const [data, setData] = useState<T>();
// Turn objects into strings for useCallback & useEffect dependencies
const [stringifiedUrl, stringifiedInit] = [JSON.stringify(url), JSON.stringify(init)];
// If no processing function is passed just cast the object to type T
// The callback hook ensures that the function is only created once
// and hence the effect hook below doesn't start an infinite loop
const processJson = useCallback(processData || ((jsonBody: any) => jsonBody as T), []);
useEffect(() => {
// Define asynchronous function
const fetchApi = async () => {
try {
// Fetch data from REST API
const response = await fetch(url, init);
if (response.status === 200) {
// Extract json
const rawData: any = await response.json();
const processedData = processJson(rawData);
setData(processedData);
} else {
console.error(`Error ${response.status} ${response.statusText}`);
}
} catch (error) {
console.error(`Error ${error}`);
}
};
// Call async function
fetchApi();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [stringifiedUrl, stringifiedInit, processJson]);
return data;
};
// DogImage.tsx
import React, { FC } from "react";
import { useFetch } from "./useFetch";
type DogImageType = { message: string; status: string };
export const DogImage: FC = () => {
const data = useFetch<DogImageType>({
url: "https://dog.ceo/api/breed/beagle/images/random"
});
return <>{data ? <img src={data.message} alt="dog"></img> : <div>Loading</div>}</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment