Untitled
1 week ago in Plain Text
import {useState, useCallback} from 'react'

export const useHttp = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const request = useCallback(async (url, method ='GET', body = null, headers= {}) => {
setLoading(true)
try{
if(body){
body = JSON.stringify(body)
headers['Content-Type'] = 'application/json'
}

const response = await fetch(url, {method, body, headers})
const data = await response.json()

if(!response.ok) {
throw new Error(data.message || 'Что-то пошло не так')
}

setLoading(false)

return data
}
catch (e){
setLoading(false)
setError(e.message)
throw e
}
}, [])

const clearError = useCallback(() => setError(null), [])

return { loading, request, error, clearError }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36