Skip to content

Instantly share code, notes, and snippets.

@rcerrejon
Last active June 3, 2019 12:31
Show Gist options
  • Save rcerrejon/04677293787cf7bdaca7c44bad87bb8d to your computer and use it in GitHub Desktop.
Save rcerrejon/04677293787cf7bdaca7c44bad87bb8d to your computer and use it in GitHub Desktop.
React Hook API Fetch Helper with axios and Typescript
import { useState, useEffect, useReducer } from 'react'
import axios from 'axios'
/* eslint-disable react-hooks/rules-of-hooks */
type Action =
| { type: 'FETCH_INIT'; payload: [] }
| { type: 'FETCH_SUCCESS'; payload: [] }
| { type: 'FETCH_FAILURE'; payload: [] }
const requestHelper = (initialUrl: string) => {
const [url] = useState(initialUrl)
const HEADERS = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
}
const [state, dispatch] = useReducer(requestReducer, {
isInit: true,
isLoading: false,
isSuccess: false,
isError: false,
data: []
})
useEffect(() => {
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT', payload: [] })
try {
await axios(url, HEADERS).then(result => dispatch({ type: 'FETCH_SUCCESS', payload: result.data }))
} catch (error) {
dispatch({ type: 'FETCH_FAILURE', payload: [] })
}
}
fetchData()
}, [HEADERS, url])
return { ...state }
}
const requestReducer = (
state: { isInit: boolean; isLoading: boolean; isSuccess: boolean; isError: boolean; data: [] },
action: Action
) => {
switch (action.type) {
case 'FETCH_INIT':
return {
...state,
isInit: false,
isLoading: true,
isError: false
}
case 'FETCH_SUCCESS':
return {
...state,
isInit: false,
isLoading: false,
isSuccess: true,
isError: false,
data: action.payload
}
case 'FETCH_FAILURE':
return {
...state,
isInit: false,
isLoading: false,
isError: true
}
default:
throw new Error()
}
}
export default requestHelper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment