Skip to content

Instantly share code, notes, and snippets.

@andrecalvo
Created June 27, 2019 13:51
Show Gist options
  • Save andrecalvo/ea5a1624025928e033e6063c85a018a3 to your computer and use it in GitHub Desktop.
Save andrecalvo/ea5a1624025928e033e6063c85a018a3 to your computer and use it in GitHub Desktop.
Custom react hook for calling a data endpoint
import { useEffect, useState, useRef } from "react";
export const useDataApi = () => {
const firstUpdate = useRef(true);
const [error, setError] = useState(false);
const [apiUrl, setApiUrl] = useState("");
const [data, setData] = useState(null);
useEffect(() => {
if (!firstUpdate.current) {
fetch(apiUrl)
.then(response => response.json())
.then(response => {
setData(response);
})
.catch(error => {
setError(true);
});
}
firstUpdate.current = false;
}, [apiUrl]);
return { data, error, callApi: setApiUrl };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment