From 010febd1b3dde2bdac2f246156724bbb2571932b Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Mon, 29 Nov 2021 18:40:12 +0800 Subject: [PATCH] feat(useCookie): support default value (#2147) --- packages/nuxt3/src/app/composables/cookie.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/nuxt3/src/app/composables/cookie.ts b/packages/nuxt3/src/app/composables/cookie.ts index ad18a17d04..3570cedbca 100644 --- a/packages/nuxt3/src/app/composables/cookie.ts +++ b/packages/nuxt3/src/app/composables/cookie.ts @@ -7,9 +7,11 @@ import destr from 'destr' import { useNuxtApp } from '#app' type _CookieOptions = Omit + export interface CookieOptions extends _CookieOptions { decode?(value: string): T encode?(value: T): string; + default?: () => T } export interface CookieRef extends Ref {} @@ -23,10 +25,10 @@ export function useCookie (name: string, _opts?: CookieOptions): C const opts = { ...CookieDefaults, ..._opts } const cookies = readRawCookies(opts) - const cookie = ref(cookies[name]) + const cookie = ref(cookies[name] ?? _opts.default?.()) if (process.client) { - watch(cookie, () => { writeClientCookie(name, cookie.value, opts) }) + watch(cookie, () => { writeClientCookie(name, cookie.value, opts as CookieSerializeOptions) }) } else if (process.server) { const initialValue = cookie.value const nuxtApp = useNuxtApp() @@ -38,7 +40,7 @@ export function useCookie (name: string, _opts?: CookieOptions): C }) } - return cookie + return cookie as CookieRef } // @ts-ignore @@ -70,7 +72,7 @@ function writeClientCookie (name: string, value: any, opts: CookieSerializeOptio function writeServerCookie (res: ServerResponse, name: string, value: any, opts: CookieSerializeOptions = {}) { if (res) { - // TODO: Try to smart join with exisiting Set-Cookie headers + // TODO: Try to smart join with existing Set-Cookie headers appendHeader(res, 'Set-Cookie', serializeCookie(name, value, opts)) } }