Bluesky app fork with some witchin' additions 馃挮
at jean/pds-label 50 lines 1.5 kB view raw
1import {useEffect, useState} from 'react' 2import uuid from 'react-native-uuid' 3 4import {onAppStateChange} from '#/lib/appState' 5import {isSessionIdExpired} from '#/analytics/identifiers/util' 6import {device} from '#/storage' 7 8let sessionId = (() => { 9 const existing = device.get(['nativeSessionId']) 10 const lastEvent = device.get(['nativeSessionIdLastEventAt']) 11 const id = existing && !isSessionIdExpired(lastEvent) ? existing : uuid.v4() 12 device.set(['nativeSessionId'], id) 13 device.set(['nativeSessionIdLastEventAt'], Date.now()) 14 return id 15})() 16 17export function getInitialSessionId() { 18 return sessionId 19} 20 21/** 22 * Gets the current session ID. Freshness depends on `useSessionId` being 23 * mounted, which handles refreshing this value between foreground/background 24 * transitions. Since that's mounted in `analytics/index.tsx`, this value can 25 * generally be trusted to be up to date. 26 */ 27export function getSessionId() { 28 return device.get(['nativeSessionId']) 29} 30 31export function useSessionId() { 32 const [id, setId] = useState(() => sessionId) 33 34 useEffect(() => { 35 const sub = onAppStateChange(state => { 36 if (state === 'active') { 37 const lastEvent = device.get(['nativeSessionIdLastEventAt']) 38 if (isSessionIdExpired(lastEvent)) { 39 sessionId = uuid.v4() 40 device.set(['nativeSessionId'], sessionId) 41 setId(sessionId) 42 } 43 } 44 device.set(['nativeSessionIdLastEventAt'], Date.now()) 45 }) 46 return () => sub.remove() 47 }, []) 48 49 return id 50}