Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nuxt): watch custom cookieRef values deeply #26151

Merged
merged 3 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 15 additions & 8 deletions packages/nuxt/src/app/composables/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export function useCookie<T = string | null | undefined> (name: string, _opts?:

// use a custom ref to expire the cookie on client side otherwise use basic ref
const cookie = import.meta.client && delay && !hasExpired
? cookieRef<T | undefined>(cookieValue, delay)
? cookieRef<T | undefined>(cookieValue, delay, opts.watch && opts.watch !== 'shallow')
: ref<T | undefined>(cookieValue)

if (import.meta.dev && hasExpired) {
Expand Down Expand Up @@ -123,9 +123,9 @@ export function useCookie<T = string | null | undefined> (name: string, _opts?:
return cookie as CookieRef<T>
}
/** @since 3.10.0 */
export function refreshCookie(name: string) {
export function refreshCookie (name: string) {
if (store || typeof BroadcastChannel === 'undefined') return

new BroadcastChannel(`nuxt:cookies:${name}`)?.postMessage({ refresh: true })
}

Expand Down Expand Up @@ -174,14 +174,21 @@ function writeServerCookie (event: H3Event, name: string, value: any, opts: Cook
const MAX_TIMEOUT_DELAY = 2_147_483_647

// custom ref that will update the value to undefined if the cookie expires
function cookieRef<T> (value: T | undefined, delay: number) {
function cookieRef<T> (value: T | undefined, delay: number, shouldWatch: boolean) {
let timeout: NodeJS.Timeout
let unsubscribe: (() => void) | undefined
let elapsed = 0
const internalRef = shouldWatch ? ref(value) : { value }
if (getCurrentScope()) {
onScopeDispose(() => { clearTimeout(timeout) })
onScopeDispose(() => {
unsubscribe?.()
clearTimeout(timeout)
})
}

return customRef((track, trigger) => {
if (shouldWatch) { unsubscribe = watch(internalRef, trigger) }

function createExpirationTimeout () {
clearTimeout(timeout)
const timeRemaining = delay - elapsed
Expand All @@ -190,20 +197,20 @@ function cookieRef<T> (value: T | undefined, delay: number) {
elapsed += timeoutLength
if (elapsed < delay) { return createExpirationTimeout() }

value = undefined
internalRef.value = undefined
trigger()
}, timeoutLength)
}

return {
get () {
track()
return value
return internalRef.value
},
set (newValue) {
createExpirationTimeout()

value = newValue
internalRef.value = newValue
trigger()
}
}
Expand Down
31 changes: 29 additions & 2 deletions test/nuxt/composables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ describe('composables', () => {
'useRequestFetch',
'isPrerendered',
'useRequestHeaders',
'useCookie',
'clearNuxtState',
'useState',
'useRequestURL',
Expand All @@ -121,7 +122,6 @@ describe('composables', () => {
'preloadRouteComponents',
'reloadNuxtApp',
'refreshCookie',
'useCookie',
'useFetch',
'useHead',
'useLazyFetch',
Expand Down Expand Up @@ -628,6 +628,33 @@ describe('defineNuxtComponent', () => {
it.todo('should support Options API head')
})

describe('useCookie', () => {
it('should watch custom cookie refs', () => {
const user = useCookie('userInfo', {
default: () => ({ score: -1 }),
maxAge: 60 * 60,
})
const computedVal = computed(() => user.value.score)
expect(computedVal.value).toBe(-1)
user.value.score++
expect(computedVal.value).toBe(0)
})

it('should not watch custom cookie refs when shallow', () => {
for (const value of ['shallow', false] as const) {
const user = useCookie('shallowUserInfo', {
default: () => ({ score: -1 }),
maxAge: 60 * 60,
watch: value
})
const computedVal = computed(() => user.value.score)
expect(computedVal.value).toBe(-1)
user.value.score++
expect(computedVal.value).toBe(-1)
}
})
})

describe('callOnce', () => {
it('should only call composable once', async () => {
const fn = vi.fn()
Expand All @@ -643,7 +670,7 @@ describe('callOnce', () => {
await Promise.all([execute(), execute(), execute()])
expect(fn).toHaveBeenCalledTimes(1)

const fnSync = vi.fn().mockImplementation(() => { })
const fnSync = vi.fn().mockImplementation(() => {})
const executeSync = () => callOnce(fnSync)
await Promise.all([executeSync(), executeSync(), executeSync()])
expect(fnSync).toHaveBeenCalledTimes(1)
Expand Down