Example · Advanced
External API Integration
Integrate timepicker with external time APIs for real-world applications
API Used
These examples use TimeAPI.io to fetch current time from different timezones. You can use any API that returns time data.
Basic - Fetch and Set Time
Simple example: Fetch current time from API and set it to the timepicker on mount.
index.tstypescript
1const picker = new TimepickerUI(input, {2 clock: { type: '24h' }3});4picker.create();56async function fetchCurrentTime() {7 try {8 const res = await fetch(9 'https://timeapi.io/api/Time/current/zone?timeZone=Europe/Warsaw'10 );11 const data = await res.json();1213 const hour = String(data.hour).padStart(2, '0');14 const minutes = String(data.minute).padStart(2, '0');15 picker.setValue(`${hour}:${minutes}`);16 } catch (err) {17 console.error('Failed to fetch time:', err);18 }19}2021fetchCurrentTime();
Advanced - Auto-Refresh with Events
Advanced example: Auto-refresh time every 60 seconds with timezone selector, EventEmitter API, and error handling.
index.tstypescript
1const picker = new TimepickerUI(input, {2 clock: {3 type: '24h',4 autoSwitchToMinutes: true,5 incrementMinutes: 5,6 },7 ui: {8 theme: 'm3-green',9 animation: true,10 },11 callbacks: {12 onConfirm: (data) => console.log('Time confirmed:', data),13 onUpdate: (data) => console.log('Time updated:', data),14 },15});16picker.create();1718// EventEmitter API19picker.on('confirm', (data) => {20 console.log('Confirmed via EventEmitter:', data);21});2223async function fetchAndSetTime() {24 try {25 const res = await fetch(26 `https://timeapi.io/api/Time/current/zone?timeZone=${timezone}`27 );28 if (!res.ok) throw new Error('Failed to fetch time');2930 const data = await res.json();31 const hour = String(data.hour).padStart(2, '0');32 const minutes = String(data.minute).padStart(2, '0');3334 picker.setValue(`${hour}:${minutes}`);35 } catch (err) {36 console.error('Error:', err);37 }38}3940// Auto-refresh every 60 seconds41const interval = setInterval(fetchAndSetTime, 60000);4243// Cleanup44return () => {45 clearInterval(interval);46 picker.destroy();47};
Multiple Timezones with Validation
Complex example: Random timezone selection, 12h format, disabled night hours, and full EventEmitter integration.
Hours 1 AM - 5 AM are disabled. Fetches random timezone on mount.
index.tstypescript
1const picker = new TimepickerUI(input, {2 clock: {3 type: '12h',4 disabledTime: {5 hours: [1, 2, 3, 4, 5], // Disable 1 AM - 5 AM6 },7 },8 ui: {9 theme: 'dark',10 animation: true,11 backdrop: true,12 },13 labels: {14 am: 'AM',15 pm: 'PM',16 time: 'Select Time',17 },18 behavior: {19 focusTrap: true,20 focusInputAfterClose: true,21 },22 callbacks: {23 onConfirm: (data) => console.log('Time confirmed:', data),24 onError: (data) => console.error('Error:', data),25 },26});27picker.create();2829// Full EventEmitter integration30picker.on('open', () => console.log('Picker opened'));31picker.on('cancel', () => console.log('Picker cancelled'));32picker.on('select:hour', (data) => console.log('Hour selected:', data));33picker.on('select:minute', (data) => console.log('Minute selected:', data));3435async function fetchWorldTime() {36 try {37 const timezones = ['America/New_York', 'Asia/Tokyo', 'Europe/London'];38 const randomTz = timezones[Math.floor(Math.random() * timezones.length)];3940 const res = await fetch(41 `https://timeapi.io/api/Time/current/zone?timeZone=${randomTz}`42 );43 const data = await res.json();4445 const hour = data.hour % 12 || 12; // Convert to 12h46 const minutes = String(data.minute).padStart(2, '0');47 const period = data.hour >= 12 ? 'PM' : 'AM';4849 picker.setValue(`${hour}:${minutes} ${period}`);50 } catch (err) {51 console.error('Failed to fetch world time:', err);52 }53}5455fetchWorldTime();
Key Features Demonstrated
- setValue() - Set time programmatically from API
- EventEmitter API - Listen to events with on(), once(), off()
- Callback options - onConfirm, onUpdate, onError handlers
- Grouped options - clock, ui, labels, behavior, callbacks
- Auto-refresh - Update time periodically with setInterval
- Timezone support - Fetch time from different timezones
- Validation - disabledTime for restricted hours
- Error handling - Proper try/catch with user feedback
- Cleanup - Destroy picker and clear intervals in useEffect
Production Tips
- • Always handle API errors gracefully with try/catch
- • Clean up intervals and destroy pickers in React useEffect cleanup
- • Use EventEmitter API for better TypeScript support
- • Consider rate limiting and caching for frequent API calls
- • Validate time data from external APIs before setting