Skip to content

Instantly share code, notes, and snippets.

@simicd
Created August 16, 2020 18:55
Show Gist options
  • Select an option

  • Save simicd/52261f5c32a828e389257d23bf75e006 to your computer and use it in GitHub Desktop.

Select an option

Save simicd/52261f5c32a828e389257d23bf75e006 to your computer and use it in GitHub Desktop.
// useFetch.ts
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>();
// ...
// 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(() => {
// ...
}, [stringifiedUrl, stringifiedInit, processJson]);
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment