Skip to content

Instantly share code, notes, and snippets.

@01speed1
Last active September 27, 2020 23:01
Show Gist options
  • Save 01speed1/ff860b500727aafffbf84560600e6576 to your computer and use it in GitHub Desktop.
Save 01speed1/ff860b500727aafffbf84560600e6576 to your computer and use it in GitHub Desktop.
useAPI
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