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.
const picker = new TimepickerUI(input, {clock: { type: '24h' }});picker.create();async function fetchCurrentTime() {try {const res = await fetch('https://timeapi.io/api/Time/current/zone?timeZone=Europe/Warsaw');const data = await res.json();const hour = String(data.hour).padStart(2, '0');const minutes = String(data.minute).padStart(2, '0');picker.setValue(`${hour}:${minutes}`);} catch (err) {console.error('Failed to fetch time:', err);}}fetchCurrentTime();
Advanced - Auto-Refresh with Events
Advanced example: Auto-refresh time every 60 seconds with timezone selector, EventEmitter API, and error handling.
const picker = new TimepickerUI(input, {clock: {type: '24h',autoSwitchToMinutes: true,incrementMinutes: 5,},ui: {theme: 'm3-green',animation: true,},callbacks: {onConfirm: (data) => console.log('Time confirmed:', data),onUpdate: (data) => console.log('Time updated:', data),},});picker.create();// EventEmitter APIpicker.on('confirm', (data) => {console.log('Confirmed via EventEmitter:', data);});async function fetchAndSetTime() {try {const res = await fetch(`https://timeapi.io/api/Time/current/zone?timeZone=${timezone}`);if (!res.ok) throw new Error('Failed to fetch time');const data = await res.json();const hour = String(data.hour).padStart(2, '0');const minutes = String(data.minute).padStart(2, '0');picker.setValue(`${hour}:${minutes}`);} catch (err) {console.error('Error:', err);}}// Auto-refresh every 60 secondsconst interval = setInterval(fetchAndSetTime, 60000);// Cleanupreturn () => {clearInterval(interval);picker.destroy();};
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.
const picker = new TimepickerUI(input, {clock: {type: '12h',disabledTime: {hours: [1, 2, 3, 4, 5], // Disable 1 AM - 5 AM},},ui: {theme: 'dark',animation: true,backdrop: true,},labels: {am: 'AM',pm: 'PM',time: 'Select Time',},behavior: {focusTrap: true,focusInputAfterClose: true,},callbacks: {onConfirm: (data) => console.log('✅ Time confirmed:', data),onError: (data) => console.error('❌ Error:', data),},});picker.create();// Full EventEmitter integrationpicker.on('open', () => console.log('Picker opened'));picker.on('cancel', () => console.log('Picker cancelled'));picker.on('select:hour', (data) => console.log('Hour selected:', data));picker.on('select:minute', (data) => console.log('Minute selected:', data));async function fetchWorldTime() {try {const timezones = ['America/New_York', 'Asia/Tokyo', 'Europe/London'];const randomTz = timezones[Math.floor(Math.random() * timezones.length)];const res = await fetch(`https://timeapi.io/api/Time/current/zone?timeZone=${randomTz}`);const data = await res.json();const hour = data.hour % 12 || 12; // Convert to 12hconst minutes = String(data.minute).padStart(2, '0');const period = data.hour >= 12 ? 'PM' : 'AM';picker.setValue(`${hour}:${minutes} ${period}`);} catch (err) {console.error('Failed to fetch world time:', err);}}fetchWorldTime();
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