1+ /// <reference types="@react-telegram/core" />
2+ import React , { useState , useEffect } from 'react' ;
3+ import { MtcuteAdapter } from '@react-telegram/mtcute-adapter' ;
4+
5+ // Timer component with useEffect and setInterval
6+ const TimerApp = ( ) => {
7+ const [ count , setCount ] = useState ( 0 ) ;
8+ const [ isRunning , setIsRunning ] = useState ( true ) ;
9+
10+ useEffect ( ( ) => {
11+ // Only set up interval if isRunning is true
12+ if ( ! isRunning ) return ;
13+
14+ const interval = setInterval ( ( ) => {
15+ setCount ( ( prevCount ) => prevCount + 1 ) ;
16+ } , 1000 ) ;
17+
18+ // Cleanup function to clear interval
19+ return ( ) => {
20+ clearInterval ( interval ) ;
21+ } ;
22+ } , [ isRunning ] ) ; // Re-run effect when isRunning changes
23+
24+ return (
25+ < >
26+ < b > ⏱️ Timer with useEffect</ b >
27+ < br />
28+ < br />
29+ < i > Seconds elapsed: { count } </ i >
30+ < br />
31+ < br />
32+ Status: { isRunning ? '🟢 Running' : '🔴 Paused' }
33+ < br />
34+ < br />
35+ < row >
36+ < button onClick = { ( ) => setIsRunning ( ! isRunning ) } >
37+ { isRunning ? '⏸️ Pause' : '▶️ Resume' }
38+ </ button >
39+ < button onClick = { ( ) => setCount ( 0 ) } > 🔄 Reset</ button >
40+ </ row >
41+ < br />
42+ < blockquote >
43+ This example demonstrates useEffect with setInterval.
44+ The timer automatically increments every second and properly
45+ cleans up when paused or when the component unmounts.
46+ </ blockquote >
47+ </ >
48+ ) ;
49+ } ;
50+
51+ // Main bot setup
52+ async function main ( ) {
53+ // You'll need to set these environment variables
54+ const config = {
55+ apiId : parseInt ( process . env . API_ID || '0' ) ,
56+ apiHash : process . env . API_HASH || '' ,
57+ botToken : process . env . BOT_TOKEN || '' ,
58+ storage : process . env . STORAGE_PATH || '.mtcute'
59+ } ;
60+
61+ if ( ! config . apiId || ! config . apiHash || ! config . botToken ) {
62+ console . error ( 'Please set API_ID, API_HASH, and BOT_TOKEN environment variables' ) ;
63+ process . exit ( 1 ) ;
64+ }
65+
66+ const adapter = new MtcuteAdapter ( config ) ;
67+
68+ // Set up command handler for timer
69+ adapter . onCommand ( 'timer' , ( ) => < TimerApp /> ) ;
70+ adapter . onCommand ( 'start' , ( ) => (
71+ < >
72+ < b > 🤖 Timer Bot</ b >
73+ < br />
74+ < br />
75+ Welcome! This bot demonstrates useEffect with setInterval.
76+ < br />
77+ < br />
78+ Use /timer to start the timer example.
79+ </ >
80+ ) ) ;
81+
82+ // Start the bot
83+ await adapter . start ( config . botToken ) ;
84+
85+ console . log ( 'Timer bot is running! Send /start to begin.' ) ;
86+ }
87+
88+ // Run the bot
89+ main ( ) . catch ( console . error ) ;
0 commit comments