feat(tri): mémoriser les préférences de tri
This commit is contained in:
34
app/composables/usePersistedValue.ts
Normal file
34
app/composables/usePersistedValue.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { ref, watch } from 'vue'
|
||||
import { useCookie } from '#imports'
|
||||
|
||||
const parseValue = <T>(value: unknown, fallback: T): T => {
|
||||
if (value === null || value === undefined) {
|
||||
return fallback
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
try {
|
||||
return JSON.parse(value) as T
|
||||
} catch {
|
||||
return value as unknown as T
|
||||
}
|
||||
}
|
||||
return value as T
|
||||
}
|
||||
|
||||
export const usePersistedValue = <T>(key: string, fallback: T) => {
|
||||
const cookie = useCookie<string | null>(`pref:${key}`, {
|
||||
sameSite: 'lax',
|
||||
})
|
||||
const initial = parseValue(cookie.value, fallback)
|
||||
const state = ref<T>(initial)
|
||||
|
||||
watch(
|
||||
state,
|
||||
(value) => {
|
||||
cookie.value = JSON.stringify(value)
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
return state
|
||||
}
|
||||
Reference in New Issue
Block a user