fix(desktop): ignore effect replay when detecting profile switches

This commit is contained in:
brooklyn! committed 2026-09-20 04:30:35 -05:00
1 parent 1f37f5cdd9
commit 5dbe99bb83
2 files changed
+29 -4

No files matched your search

@@ -0,0 +1,24 @@
import { act, cleanup, renderHook } from '@testing-library/react'
import { atom } from 'nanostores'
import { StrictMode } from 'react'
import { afterEach, expect, it, vi } from 'vitest'
vi.mock('@/store/profile', () => ({ $activeGatewayProfile: atom('default') }))
import { $activeGatewayProfile } from '@/store/profile'
import { useOnProfileSwitch } from './use-on-profile-switch'
afterEach(cleanup)
it('ignores StrictMode effect replay and reacts only to real profile changes', () => {
const onSwitch = vi.fn()
const { rerender } = renderHook(() => useOnProfileSwitch(onSwitch), { wrapper: StrictMode })
expect(onSwitch).not.toHaveBeenCalled()
rerender()
expect(onSwitch).not.toHaveBeenCalled()
act(() => $activeGatewayProfile.set('other'))
expect(onSwitch).toHaveBeenCalledTimes(1)
act(() => $activeGatewayProfile.set('default'))
expect(onSwitch).toHaveBeenCalledTimes(2)
})
@@ -8,16 +8,17 @@ import { $activeGatewayProfile } from '@/store/profile'
* when the backend the app talks to swaps underneath a still-mounted view. */
export function useOnProfileSwitch(onSwitch: () => void): void {
const profile = useStore($activeGatewayProfile)
const first = useRef(true)
const previousProfile = useRef(profile)
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
useEffect(() => {
if (first.current) {
first.current = false
// StrictMode replays mount effects without changing the profile. Counting
// effect runs would clear a seeded settings draft and leave it loading.
if (previousProfile.current === profile) {
return
}
previousProfile.current = profile
onSwitch()
// Fire on profile change only; onSwitch identity is intentionally ignored.
// eslint-disable-next-line react-hooks/exhaustive-deps