42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
import { useCallback, useState } from 'react';
|
|
|
|
const API_BASE = process.env.NEXT_PUBLIC_API_URL?.replace(/\/$/, '') || 'http://localhost:8000';
|
|
|
|
export function useAdminApi(token) {
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState(null);
|
|
|
|
const authorizedFetch = useCallback(
|
|
async (path, options = {}) => {
|
|
setLoading(true);
|
|
setError(null);
|
|
try {
|
|
const response = await fetch(`${API_BASE}${path}`, {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Token ${token}`,
|
|
...(options.headers || {}),
|
|
},
|
|
...options,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
throw new Error(text || `Request failed ${response.status}`);
|
|
}
|
|
|
|
const isJson = response.headers.get('content-type')?.includes('application/json');
|
|
return isJson ? response.json() : null;
|
|
} catch (err) {
|
|
setError(err.message);
|
|
throw err;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
},
|
|
[token]
|
|
);
|
|
|
|
return { loading, error, request: authorizedFetch };
|
|
}
|