Created
March 11, 2020 21:59
-
-
Save fangzhzh/5aaba01babbab2159af9c3331b50513a to your computer and use it in GitHub Desktop.
This file contains 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
```javascript | |
export const useApi = (apiRequest, initialData, depend) => { | |
// const [url, setUrl] = useState(initialUrl); | |
const [isLoading, setIsLoading] = useState(true); | |
const [hasError, setHasError] = useState(false); | |
const [errorCode, setErrorCode] = useState(200); | |
const [errorMessage, setErrorMessage] = useState(""); | |
const [fetchedData, setFetchedData] = useState(initialData); | |
useEffect(() => { | |
let unmounted = false; | |
const handleFetchResponse = response => { | |
if (unmounted) return initialData; | |
setHasError(!response.ok); | |
setErrorCode(response.statusCode); | |
setErrorMessage(response.message); | |
setIsLoading(false); | |
return response.ok && response.json ? response.json() : initialData; | |
}; | |
const fetchData = () => { | |
setIsLoading(true); | |
return apiRequest | |
.then(handleFetchResponse) | |
.catch(handleFetchResponse); | |
}; | |
if (!unmounted) | |
fetchData().then(data => !unmounted && setFetchedData(data)); | |
return () => { | |
unmounted = true; | |
}; | |
}, depend); | |
return {isLoading, hasError, errorCode, errorMessage, data: fetchedData, setData: setFetchedData}; | |
}; | |
``` |
Author
fangzhzh
commented
Mar 11, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment