import { Ref } from "@nuxtjs/composition-api" import { distinctUntilChanged, pluck } from "rxjs" import DispatchingStore, { defineDispatchers } from "./DispatchingStore" import { useStream } from "~/helpers/utils/composables" type LocalState = { REMEMBERED_TEAM_ID: string | undefined } const defaultLocalState: LocalState = { REMEMBERED_TEAM_ID: undefined, } const dispatchers = defineDispatchers({ bulkApplyState(_currentState: LocalState, payload: Partial) { return payload }, applyState( _currentState: LocalState, { key, value }: { key: K; value: LocalState[K] } ) { const result: Partial = { [key]: value, } return result }, }) export const localStateStore = new DispatchingStore( defaultLocalState, dispatchers ) export const localState$ = localStateStore.subject$.asObservable() export function bulkApplyLocalState(obj: Partial) { localStateStore.dispatch({ dispatcher: "bulkApplyState", payload: obj, }) } export function applyLocalState( key: K, value: LocalState[K] ) { localStateStore.dispatch({ dispatcher: "applyState", payload: { key, value }, }) } export function useLocalState( key: K ): Ref { return useStream( localStateStore.subject$.pipe(pluck(key), distinctUntilChanged()), localStateStore.value[key], (value: LocalState[K]) => { localStateStore.dispatch({ dispatcher: "applyState", payload: { key, value }, }) } ) }