/
St.Anton
/
marvel_starter
Обзор
Документация
Войти
/
St.Anton
/
marvel_starter
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/hooks/http.hook.js
38 строк
1 KB
St.Anton
Added ComicsList & ComicsItem
01 апр 2022, 20:42
01 апр 2022, 20:42
f6896eb
Код
Авторство
О чём код?
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 = { "Content-Type": "application/json" } ) => { setLoading(true); try { const response = await fetch(url, { method, body, headers }); if (!response.ok) { throw new Error( `Could not fetch ${url}, status: ${response.status}` ); } const data = await response.json(); setLoading(false); return data; } catch (e) { setLoading(false); setError(e.message); throw e; } }, [] ); const clearError = useCallback(() => { setError(null); }, []); return { loading, request, error, clearError }; };