Created
March 15, 2019 00:26
-
-
Save pmonty/fa919a54aa6c6df7cbd1024d1e9de17c to your computer and use it in GitHub Desktop.
useAxious
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
import axios from 'axios' | |
import { useEffect, useReducer, useState } from 'react' | |
const initialResponse = { response: null, error: null, loading: false } | |
function responseReducer(state, action) { | |
switch (action.type) { | |
case 'INIT': | |
return { response: null, error: null, loading: true } | |
case 'SUCCESS': | |
return { response: action.payload, error: null, loading: false } | |
case 'FAIL': | |
return { response: null, error: action.payload, loading: false } | |
default: | |
return initialResponse | |
} | |
} | |
const { CancelToken } = axios | |
export function useAxios({ | |
url, | |
method = 'get', | |
options = {}, | |
headers = {}, | |
trigger, | |
anotherTrigger, | |
}) { | |
const [results, dispatch] = useReducer(responseReducer, initialResponse) | |
const [innerTrigger, setInnerTrigger] = useState(0) | |
let outerTrigger = trigger | |
outerTrigger = JSON.stringify(trigger) | |
dispatch({ type: 'INIT' }) | |
useEffect(() => { | |
if (!url) { | |
return | |
} | |
const source = CancelToken.source() | |
axios({ | |
url, | |
method, | |
...options, | |
...headers, | |
cancelToken: source.token, | |
}) | |
.then(r => { | |
dispatch({ type: 'SUCCESS', payload: r }) | |
}) | |
.catch(e => { | |
dispatch({ type: 'FAIL', payload: e }) | |
}) | |
return () => { | |
source.cancel() | |
} | |
}, [innerTrigger, outerTrigger]) | |
return { | |
...results, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment