Skip to content

Commit

Permalink
fixed Storage, fixed changed datatyype, fixed deep object, fixed toRaw
Browse files Browse the repository at this point in the history
  • Loading branch information
Dreamlinerm committed Jan 8, 2025
1 parent ebae6ed commit bc4924f
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions src/composables/useBrowserStorage.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,46 @@
import { ref, watch } from 'vue'

import { ref, watch } from "vue"
export function useBrowserSyncStorage<T>(key: string, defaultValue: T) {
const data = ref<T>(defaultValue)

// Initialize storage with the value from chrome.storage.sync
chrome.storage.sync.get(key, (result) => {
if (result[key] !== undefined) {
if (
result?.[key] != undefined &&
typeof result[key] === typeof defaultValue
) {
data.value = result[key]
}
})

// Watch for changes in the storage and update chrome.storage.sync
watch(data, (newValue) => {
chrome.storage.sync.set({ [key]: newValue })
})

watch(
data,
(newValue) => {
chrome.storage.sync.set({ [key]: toRaw(newValue) })
},
{ deep: true },
)
return data
}

export function useBrowserLocalStorage<T>(key: string, defaultValue: T) {
const data = ref<T>(defaultValue)

// Initialize storage with the value from chrome.storage.local
chrome.storage.local.get(key, (result) => {
if (result[key] !== undefined) {
if (
result?.[key] != undefined &&
typeof result[key] === typeof defaultValue
) {
data.value = result[key]
}
})

// Watch for changes in the storage and update chrome.storage.sync
watch(data, (newValue) => {
chrome.storage.local.set({ [key]: newValue })
})

// Watch for changes in the storage and update chrome.storage.local
watch(
data,
(newValue) => {
chrome.storage.local.set({ [key]: toRaw(newValue) })
},
{ deep: true },
)
return data
}

0 comments on commit bc4924f

Please sign in to comment.