Skip to content

Instantly share code, notes, and snippets.

@fangzhzh
Created March 11, 2020 21:59
Show Gist options
  • Save fangzhzh/5aaba01babbab2159af9c3331b50513a to your computer and use it in GitHub Desktop.
Save fangzhzh/5aaba01babbab2159af9c3331b50513a to your computer and use it in GitHub Desktop.
```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};
};
```
@fangzhzh
Copy link
Author

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};
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment