Skip to content

Instantly share code, notes, and snippets.

@lorens-osman-dev
Created November 21, 2024 17:49
Show Gist options
  • Save lorens-osman-dev/13921b96ec95b12c602fce0328a8220e to your computer and use it in GitHub Desktop.
Save lorens-osman-dev/13921b96ec95b12c602fce0328a8220e to your computer and use it in GitHub Desktop.
import { createPinia, defineStore } from "pinia";
import { ref, type Ref, type UnwrapRef } from "vue";
const pinia = createPinia();
export const newStore = <T>(storeName: string, value: T) => {
const start = defineStore(storeName, () => {
const state = ref(value);
function update(newValue: UnwrapRef<T>) {
state.value = newValue;
}
return { state, update };
});
const store = start(pinia);
return store;
};
class GlobalStore<G> {
stores: { [key: string]: ReturnType<typeof newStore<G>> } = {};
storeNames: string[] = [];
set(storeName: string, value: G): void {
if (!this.stores[storeName]) {
this.stores[storeName] = newStore<G>(storeName, value);
this.storeNames.push(storeName);
}
}
}
const globalStore = new GlobalStore();
export default globalStore;
const _ = new GlobalStore();
//usage
_.set("bigStore", 45);
_.set("nameStore", "lorens");
console.log(_.stores.bigStore.state); //45
console.log(_.stores.nameStore.state); //lorens
_.stores.bigStore.update(88);
_.stores.nameStore.update("ahmed");
console.log(_.stores.bigStore.state); //88
console.log(_.stores.nameStore.state); //ahmed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment