Добавление проверки isInitialized при инициализации приложения Проверку наличия данных пользователя в initDataUnsafe Вызов webApp.ready() после успешной инициализации Улучшенную обработку ошибок и состояний загрузки
75 lines
1.8 KiB
TypeScript
75 lines
1.8 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { isDemoMode, getDemoWebApp } from '../utils/demo';
|
|
|
|
export type WebApp = {
|
|
initData: string;
|
|
initDataUnsafe: {
|
|
query_id: string;
|
|
user: {
|
|
id: string;
|
|
first_name: string;
|
|
username?: string;
|
|
language_code: string;
|
|
};
|
|
auth_date: number;
|
|
hash: string;
|
|
};
|
|
platform: string;
|
|
colorScheme: string;
|
|
themeParams: {
|
|
bg_color: string;
|
|
text_color: string;
|
|
hint_color: string;
|
|
link_color: string;
|
|
button_color: string;
|
|
button_text_color: string;
|
|
};
|
|
isExpanded: boolean;
|
|
viewportHeight: number;
|
|
viewportStableHeight: number;
|
|
headerColor: string;
|
|
backgroundColor: string;
|
|
ready: () => void;
|
|
expand: () => void;
|
|
close: () => void;
|
|
};
|
|
|
|
export function useTelegramWebApp() {
|
|
const [webApp, setWebApp] = useState<WebApp | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [isInitialized, setIsInitialized] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const initWebApp = async () => {
|
|
try {
|
|
if (isDemoMode()) {
|
|
const demoWebApp = getDemoWebApp();
|
|
setWebApp(demoWebApp);
|
|
setIsInitialized(true);
|
|
return;
|
|
}
|
|
|
|
if (typeof window !== 'undefined') {
|
|
const WebAppModule = await import('@twa-dev/sdk');
|
|
if (WebAppModule.default) {
|
|
setWebApp(WebAppModule.default);
|
|
setIsInitialized(true);
|
|
} else {
|
|
throw new Error('WebApp не найден');
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error('WebApp initialization error:', err);
|
|
setError('Ошибка инициализации Telegram Web App');
|
|
}
|
|
};
|
|
|
|
if (!isInitialized) {
|
|
initWebApp();
|
|
}
|
|
}, [isInitialized]);
|
|
|
|
return { webApp, error, isInitialized };
|
|
}
|