'use client'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useFetch } from '@gitroom/helpers/utils/custom.fetch'; import useSWR from 'swr'; import { Slider } from '@gitroom/react/form/slider'; import { useToaster } from '@gitroom/react/toaster/toaster'; import { useT } from '@gitroom/react/translation/get.transation.service.client'; interface EmailNotifications { sendSuccessEmails: boolean; sendFailureEmails: boolean; sendStreakEmails: boolean; } export const useEmailNotifications = () => { const fetch = useFetch(); const load = useCallback(async () => { return (await fetch('/user/email-notifications')).json(); }, []); return useSWR('email-notifications', load, { revalidateOnFocus: false, revalidateOnReconnect: false, revalidateIfStale: false, revalidateOnMount: true, refreshWhenHidden: false, refreshWhenOffline: false, }); }; const EmailNotificationsComponent = () => { const t = useT(); const fetch = useFetch(); const toaster = useToaster(); const { data, isLoading } = useEmailNotifications(); const [localSettings, setLocalSettings] = useState({ sendSuccessEmails: true, sendFailureEmails: true, sendStreakEmails: true, }); // Keep a ref to always have the latest state const settingsRef = useRef(localSettings); settingsRef.current = localSettings; // Sync local state with fetched data useEffect(() => { if (data) { setLocalSettings(data); } }, [data]); const updateSetting = useCallback( async (key: keyof EmailNotifications, value: boolean) => { // Use ref to get the latest state const currentSettings = settingsRef.current; const newData = { ...currentSettings, [key]: value, }; // Update local state immediately setLocalSettings(newData); await fetch('/user/email-notifications', { method: 'POST', body: JSON.stringify(newData), }); toaster.show(t('settings_updated', 'Settings updated'), 'success'); }, [] ); const handleSuccessEmailsChange = useCallback( (value: 'on' | 'off') => { updateSetting('sendSuccessEmails', value === 'on'); }, [updateSetting] ); const handleFailureEmailsChange = useCallback( (value: 'on' | 'off') => { updateSetting('sendFailureEmails', value === 'on'); }, [updateSetting] ); const handleStreakEmailsChange = useCallback( (value: 'on' | 'off') => { updateSetting('sendStreakEmails', value === 'on'); }, [updateSetting] ); if (isLoading) { return (
{t('loading', 'Loading...')}
); } return (
{t('email_notifications', 'Email Notifications')}
{t('success_emails', 'Success Emails')}
{t( 'success_emails_description', 'Receive email notifications when posts are published successfully' )}
{t('failure_emails', 'Failure Emails')}
{t( 'failure_emails_description', 'Receive email notifications when posts fail to publish' )}
{t('streak_emails', 'Streak Reminder Emails')}
{t( 'streak_emails_description', 'Receive email reminders when your posting streak is about to end' )}
); }; export default EmailNotificationsComponent;