Last active
March 16, 2020 18:29
-
-
Save kettanaito/d93c6bb6b5c005656a46ee283cd8af7f to your computer and use it in GitHub Desktop.
useFetch React hook
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 React from 'react' | |
import { useFetch } from './hooks/useFetch' | |
const Example = () => { | |
const { data, loading, error } = useFetch('https://api.github.com/user/octocat') | |
if (loading) { | |
return <Spinner /> | |
} | |
if (error) { | |
errors.display(error) | |
return null | |
} | |
return ( | |
<div> | |
<h1>{data.login}</h1> | |
</div> | |
) | |
} |
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 { useReducer, useEffect, useCallback } from 'react' | |
const fetchReducer = (state, action) => { | |
switch (action.type) { | |
case "FETCH_START": { | |
return { | |
loading: true, | |
data: null, | |
error: null | |
}; | |
} | |
case "FETCH_ERROR": { | |
return { | |
loading: false, | |
data: null, | |
error: action.error | |
}; | |
} | |
case "FETCH_END": { | |
return { | |
loading: false, | |
data: action.data | |
}; | |
} | |
default: | |
return state; | |
} | |
}; | |
export const useFetch = url => { | |
const [state, dispatch] = useReducer( | |
fetchReducer, | |
{ | |
loading: false, | |
error: null, | |
data: null | |
} | |
); | |
const refetch = useCallback(() => { | |
dispatch({ type: "FETCH_START" }); | |
fetch(url) | |
.then(res => res.json()) | |
.then(data => dispatch({ type: "FETCH_END", data })) | |
.catch(error => dispatch({ type: "FETCH_ERROR", error })); | |
}, [url]) | |
useEffect(() => { | |
refetch(url); | |
}, [url]); | |
return { | |
data: state.data, | |
error: state.error, | |
refetch | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment