Skip to content

Instantly share code, notes, and snippets.

@amorkovin
Created June 14, 2021 08:12
Show Gist options
  • Save amorkovin/7fa33d79f43586d92c329f66550f7dcd to your computer and use it in GitHub Desktop.
Save amorkovin/7fa33d79f43586d92c329f66550f7dcd to your computer and use it in GitHub Desktop.
Hook ajax react
// Тестовый ajax-запрос
// Использование хука
const {loading, request, error, cleanError} = useHttp();
const testAjaxHandler = async () => {
try {
const data = await request(
'http://localhost:8000/api/api123',
'POST',
{test: 123},
);
console.log(data);
} catch (e) {}
}
// Кнопка в редндере отображения, выполняющая запрос при клике
<button onClick={testAjaxHandler}>Test ajax</button>
src/hooks/http.hook.js
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 || 'Error in ajax');
}
setLoading(false);
return data;
} catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
}, []);
const cleanError = useCallback(() => setError(null), []);
return {loading, request, error, cleanError};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment