API Integration
Make API calls using built-in utilities and React Query.
API Utilities
import { apiGet, apiPost, apiPut, apiDelete } from 'ez-console';
// GET request
const products = await apiGet('/products');
// POST request
const newProduct = await apiPost('/products', {
name: 'Product Name',
price: 99.99,
});
// PUT request
const updated = await apiPut(`/products/${id}`, {
name: 'New Name',
});
// DELETE request
await apiDelete(`/products/${id}`);
Using with React Query (ahooks)
import { useRequest } from 'ahooks';
import { apiGet, apiPost } from 'ez-console';
function ProductList() {
// Fetch data
const { data, loading, error } = useRequest(() => apiGet('/products'));
// Mutation
const { run: createProduct, loading: creating } = useRequest(
(values) => apiPost('/products', values),
{
manual: true,
onSuccess: () => {
message.success('Product created');
},
}
);
if (loading) return <Spin />;
if (error) return <Alert message="Error loading products" />;
return (
<div>
{data.map(product => (
<div key={product.id}>{product.name}</div>
))}
</div>
);
}
With Pagination
const { data, loading } = useRequest(
({ current, pageSize }) => apiGet('/products', {
params: { page: current, page_size: pageSize }
}),
{
defaultParams: [{ current: 1, pageSize: 10 }],
}
);
// Response format:
// {
// code: "0",
// data: [...],
// total: 100,
// current: 1,
// page_size: 10
// }
Error Handling
const { data, error } = useRequest(
() => apiGet('/products'),
{
onError: (error) => {
if (error.response?.status === 401) {
// Handle unauthorized
window.location.href = '/login';
} else {
message.error(error.response?.data?.err || 'An error occurred');
}
},
}
);
Request Interceptors
Requests automatically include:
- Authorization header (Bearer token)
- Content-Type: application/json
- CSRF token (if configured)
Response Interceptors
Responses are automatically handled:
- Token refresh on 401
- Error message extraction
- Loading state management
Next Steps
- Manage state
- Create forms
- Use built-in components