Files
simply_cpq/buildtime/client/logical-editor/src/components/tools/UseFetch.jsx
T

29 lines
1023 B
React

import { useState, useEffect } from 'react'
function UseFetch(url, options = {method: 'GET'}) {
const [data, setData] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
console.log('UseFetch: useEffect called with url =', url, 'options =', options)
setIsLoading(true)
setError(null)
fetch(url, options)
.then((response) => {
if (!response.ok) {
console.log('UseFetch: response not ok, status =', response.status)
throw new Error(`HTTP error! status: ${response.status}`)
}
return response.json()
})
.then((json) => setData(json))
.catch((err) => setError(err.message))
.finally(() => setIsLoading(false))
},[])
return { data, isLoading, error }
}
export default UseFetch