'use client'; import React, { useCallback, useEffect, useState } from 'react'; import { useFetch } from '@gitroom/helpers/utils/custom.fetch'; import useSWR from 'swr'; import { Select } from '@gitroom/react/form/select'; import { useToaster } from '@gitroom/react/toaster/toaster'; import { useT } from '@gitroom/react/translation/get.transation.service.client'; type ShortLinkPreference = 'ASK' | 'YES' | 'NO'; interface ShortlinkPreferenceResponse { shortlink: ShortLinkPreference; } export const useShortlinkPreference = () => { const fetch = useFetch(); const load = useCallback(async () => { return (await fetch('/settings/shortlink')).json(); }, []); return useSWR('shortlink-preference', load, { revalidateOnFocus: false, revalidateOnReconnect: false, revalidateIfStale: false, revalidateOnMount: true, refreshWhenHidden: false, refreshWhenOffline: false, }); }; const ShortlinkPreferenceComponent = () => { const t = useT(); const fetch = useFetch(); const toaster = useToaster(); const { data, isLoading, mutate } = useShortlinkPreference(); const [localValue, setLocalValue] = useState('ASK'); // Sync local state with fetched data useEffect(() => { if (data?.shortlink) { setLocalValue(data.shortlink); } }, [data]); const handleChange = useCallback( async (event: React.ChangeEvent) => { const newValue = event.target.value as ShortLinkPreference; // Update local state immediately setLocalValue(newValue); await fetch('/settings/shortlink', { method: 'POST', body: JSON.stringify({ shortlink: newValue }), }); mutate({ shortlink: newValue }); toaster.show(t('settings_updated', 'Settings updated'), 'success'); }, [fetch, mutate, toaster, t] ); if (isLoading) { return (
{t('loading', 'Loading...')}
); } return (
{t('shortlink_settings', 'Shortlink Settings')}
{t('shortlink_preference', 'Shortlink Preference')}
{t( 'shortlink_preference_description', 'Control how URLs in your posts are handled. Shortlinks provide click statistics.' )}
); }; export default ShortlinkPreferenceComponent;