Skip to content

Instantly share code, notes, and snippets.

@simicd
Created August 16, 2020 19:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simicd/bbf37fe119c7b344634e4d47d2709fea to your computer and use it in GitHub Desktop.
Save simicd/bbf37fe119c7b344634e4d47d2709fea to your computer and use it in GitHub Desktop.
import { useState, useEffect, useCallback } from "react";
export const useFetch = ({ url, init, processData }) => {
// Response state
const [data, setData] = useState();
// Turn objects into strings for useCallback & useEffect dependencies
const [stringifiedUrl, stringifiedInit] = [JSON.stringify(url), JSON.stringify(init)];
// If no processing function is passed just return the data
// 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) => jsonBody), []);
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 = 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;
};
import React from "react";
import { useFetch } from "./useFetch";
export const DogImage = () => {
const data = useFetch({
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