Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Last active March 16, 2020 18:29
Show Gist options
  • Save kettanaito/d93c6bb6b5c005656a46ee283cd8af7f to your computer and use it in GitHub Desktop.
Save kettanaito/d93c6bb6b5c005656a46ee283cd8af7f to your computer and use it in GitHub Desktop.
useFetch React hook
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>
)
}
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