Created
June 27, 2019 13:51
-
-
Save andrecalvo/ea5a1624025928e033e6063c85a018a3 to your computer and use it in GitHub Desktop.
Custom react hook for calling a data endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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