Cookie
In the below code example you can see how you can create a cookie composable and how you can use this in your Nuxt 3 app.
use-stateful-cookie.ts
import type { CookieOptions } from '#app'
/**
* Manage a stateful cookie
*
* This composable should not be necessary when this issue is fixed:
* https://github.com/nuxt/framework/issues/2416
*/
export default function useStatefulCookie<T>(
name: string,
options?: CookieOptions<T>
) {
const cookie = useCookie<T>(name, options as CookieOptions<T> & { readonly?: false | undefined; })
const state = useState<T>(name, () => cookie.value)
watch(
state,
() => {
cookie.value = state.value
},
{
deep: true
}
)
return state
}