Last active
September 27, 2020 23:01
-
-
Save 01speed1/ff860b500727aafffbf84560600e6576 to your computer and use it in GitHub Desktop.
useAPI
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 React, { useState, useEffect } from 'react' | |
const defaualtAPIConfig = config => { | |
return Object.assign( | |
{ | |
method: 'POST', | |
mode: 'same-origin', | |
cache: 'no-cache', | |
credentials: 'same-origin', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
redirect: 'follow', | |
referrerPolicy: 'same-origin', | |
body: JSON.stringify({}) | |
}, | |
config | |
) | |
} | |
export default function useAPI(url, method, body) { | |
const [response, setResponse] = useState(null) | |
const [error, setError] = useState(null) | |
const [loading, setLoading] = useState(false) | |
useEffect(() => { | |
const fetchData = async () => { | |
setLoading(true) | |
try { | |
const res = await fetch( | |
url, | |
defaualtAPIConfig({ method, body: JSON.stringify(body) }) | |
) | |
const json = await res.json() | |
setResponse(json) | |
setError(null) | |
setLoading(false) | |
} catch (error) { | |
setResponse(null) | |
setError(error) | |
setLoading(false) | |
} | |
} | |
fetchData() | |
}, [url, method, body]) | |
return { response, error, loading } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment