NextNodeTemplate/frontend/components/ExampleComponent.tsx

71 lines
1.7 KiB
TypeScript
Raw 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 {
const response = await apiRequest<ApiData>('example', {
method: 'POST',
body: JSON.stringify({
name: 'Test',
value: '123',
}),
});
if (response.success && response.data) {
setData(response.data);
} else {
setError(response.error || 'Unknown error');
}
} 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>
);
}