-
Considering that storage API is really bad DX, making a wrapper sounds reasonable. I wonder how do you guys do it, is there anything out there to simplify the storage API and make it reactive out of the box? I know about Feels like major important part of building the extensions, but I think web would disagree with me, cause I wasn't able to find anything. Please share with me if you have something already made, npm package, repository, anything... Much appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here are some libraries:
I couldn't find any that integrate with Vue. I also plan on adding a storage wrapper and messaging wrapper to WXT in the future. The storage API would use
// composables/useStoredValue.ts
import { UseAsyncStateOptions, useAsyncState } from "@vueuse/core";
import useStorage from "./useStorage";
import { computed, onMounted, onUnmounted, ref } from "vue";
export default function <
T extends StorageValue,
Shallow extends boolean = true
>(
key: string,
initialValue?: T,
opts?: UseAsyncStateOptions<Shallow, T | null>
) {
const storage = useStorage();
const { state, ...asyncState } = useAsyncState<T | null, [], Shallow>(
() => storage.getItem(key),
initialValue ?? null,
opts
);
// Listen for changes
let unwatch: Promise<() => void> | undefined;
onMounted(() => {
unwatch = storage.watch(async (event, changedKey) => {
if (key !== changedKey) return;
if (event === "remove") state.value = null;
else asyncState.execute();
});
});
onUnmounted(() => {
unwatch?.then((fn) => fn());
});
return {
// Use a writable computed ref to write updates to storage
state: computed({
get() {
return state.value;
},
set(newValue) {
void storage.setItem(key, newValue);
state.value = newValue;
},
}),
...asyncState,
};
}
type StorageValue = null | string | number | boolean | object; This is reactive and supports writing to storage when you set the value from a component. Here's some example usages: const { state: count } = useStoredValue("session:count", 0);
function onClick() {
count.value++;
}
const { state: installDate } = useStoredValue("local:install-date"); If you have any opinions on what a storage API might look like, please leave them on #228! |
Beta Was this translation helpful? Give feedback.
Here are some libraries:
localStorage
-esk APIs for chrome extensions. I wrote this, but it useswebextension-polyfill
, so I know you won't want to use it lolI couldn't find any that integrate with Vue.
I also plan on adding a storage wrapper and messaging wrapper to WXT in the future. The storage API would use
unstorage
, see #228 for more details.unstorage
works with Vueuse'suseStorageAsync
, but like you said, it's not reactiv…