Local Storage With Composables

Coding | January 2024Read in Outline

import type { MixwayPoint } from '~/types/mixway/point'

const KEY = 'location-search-history'
export const useLocationSearchHistory = () => {
    let isInitialized = ref(false)
    const data = useState<MixwayPoint[]>(KEY, () => [])

    const parseData = (data?: string | null) => {
        try {
            if (!data) return []
            return JSON.parse(data)
        } catch {
            return []
        }
    }

    const handleUpdateStorage = (e: StorageEvent) => {
        console.log('storage event')
        if (e.key !== KEY) return
        data.value = parseData(e.newValue)
    }

    onMounted(() => {
        data.value = parseData(localStorage.getItem(KEY))
        window.addEventListener('storage', handleUpdateStorage)
        isInitialized.value = true
    })

    onUnmounted(() => {
        window.removeEventListener('storage', handleUpdateStorage)
    })

    watch(
        () => data.value,
        () => {
            if (!isInitialized) return
            localStorage.setItem(KEY, JSON.stringify(data.value))
        }
    )
    return data
}

© 2023-2024 HamP, Assets used in the site belongs to respective owner | View Source