This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/website/hooks/useAPI.js

31 lines
712 B
JavaScript
Raw Normal View History

2020-08-03 12:04:07 +02:00
import { useEffect, useState } from 'react'
import api from '../utils/api'
2020-03-21 16:43:37 +01:00
/**
2020-08-03 12:04:07 +02:00
* @param {String} url
* @param {*} defaultData
* @param {String} method
* @param {Object} options
2020-03-21 16:43:37 +01:00
*/
2020-08-03 12:04:07 +02:00
function useAPI (url, defaultData = [], method = 'get', options = {}) {
const [isLoading, setIsLoading] = useState(true)
const [data, setData] = useState(defaultData)
const [hasError, setHasError] = useState(false)
2020-03-21 16:43:37 +01:00
2020-08-03 12:04:07 +02:00
useEffect(() => {
api[method](url, options)
.then((result) => {
setData(result.data)
setIsLoading(false)
})
.catch((error) => {
setHasError(true)
console.error(error)
})
}, [])
2020-03-21 16:43:37 +01:00
2020-08-03 12:04:07 +02:00
return [isLoading, data, hasError]
2020-03-21 16:43:37 +01:00
}
2020-08-03 12:04:07 +02:00
export default useAPI