NextNodeTemplate/frontend/components/ExampleComponent.tsx
2025-11-02 17:12:42 +03:00

83 lines
2.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Пример React компонента с использованием API
'use client';
import { useState } from 'react';
import { apiRequest } from '@/lib/api';
interface ApiData {
name: string;
value: string;
}
export default function ExampleComponent() {
const [data, setData] = useState<ApiData | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleFetch = async () => {
setLoading(true);
setError(null);
try {
// Используем правильный endpoint с валидацией: /api/example/data
const response = await apiRequest<ApiData>('example/data', {
method: 'POST',
body: JSON.stringify({
name: 'Test',
value: 123, // Число, а не строка (валидатор требует numeric)
}),
});
if (response.success && response.data) {
setData({
name: response.data.name,
value: String(response.data.value), // Преобразуем для отображения
});
} else {
// Улучшенная обработка ошибок валидации
let errorMessage = response.error || 'Unknown error';
if (response.errors && Array.isArray(response.errors)) {
const validationErrors = response.errors
.map((err: { msg?: string }) => err.msg || err)
.join(', ');
errorMessage = `Ошибка валидации: ${validationErrors}`;
}
setError(errorMessage);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch data');
} finally {
setLoading(false);
}
};
return (
<div className="p-4 bg-gray-700 rounded-lg">
<h2 className="text-xl font-semibold mb-4">Пример компонента</h2>
<button
onClick={handleFetch}
disabled={loading}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 rounded"
>
{loading ? 'Загрузка...' : 'Получить данные'}
</button>
{error && (
<div className="mt-4 p-2 bg-red-800 text-red-200 rounded">
Ошибка: {error}
</div>
)}
{data && (
<div className="mt-4 p-2 bg-green-800 text-green-200 rounded">
<p>Name: {data.name}</p>
<p>Value: {data.value}</p>
</div>
)}
</div>
);
}