All files / src useUserPreferences.ts

76.47% Statements 13/17
60% Branches 6/10
80% Functions 4/5
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                  2x 2x 2x 2x   2x 2x 2x 2x 2x 2x             2x 2x        
import { useEffect } from 'react'
import type { components } from './api'
import { applyUserLanguage } from './i18n'
import { applyTheme, THEME_MODES } from './theme'
import { SessionExpiredError, useApi } from './useApi'
 
type UserProfile = components['schemas']['UserProfile']
 
export function useUserPreferences() {
	const apiFetch = useApi()
	useEffect(() => {
		let cancelled = false
		apiFetch('/users/profile')
			.then(async (res) => {
				Iif (!res.ok) return
				const userProfile = (await res.json()) as UserProfile
				Iif (cancelled) return
				applyUserLanguage(userProfile.preferences?.language)
				const theme = userProfile.preferences?.theme
				if (theme && THEME_MODES.includes(theme)) applyTheme(theme)
			})
			.catch((e) => {
				if (e instanceof SessionExpiredError) return
				// a failed lookup shouldn't break the app (except for ProfilePage where this is explicitly handled)
			})
 
		return () => {
			cancelled = true
		}
	}, [apiFetch])
}