Skip to content

Instantly share code, notes, and snippets.

@scvnc
Last active July 13, 2022 19:33
Show Gist options
  • Save scvnc/1d2e6c9f7a1784db89d3af6f0cbe02c6 to your computer and use it in GitHub Desktop.
Save scvnc/1d2e6c9f7a1784db89d3af6f0cbe02c6 to your computer and use it in GitHub Desktop.
An RxJS-only implementation of the AlertStore example during the Pinia demo from VueForge 2022
import { useObservable } from '@/helpers/rxjs-helper';
import { computed } from '@vue/composition-api';
import { BehaviorSubject } from 'rxjs';
interface Alert {
id: number;
text: string;
}
interface AlertsStoreState {
alerts: Alert[];
}
// createState doesn't have a way for us to easily get the current value of the state, a flaw IMO.
// so lets just use BehaviorSubject :)
const _state = new BehaviorSubject<AlertsStoreState>({ alerts: [] });
// Actions on the store
const notify = (message: string) => {
const currentState = _state.value;
const newState: AlertsStoreState = {
...currentState,
alerts: currentState.alerts.concat([{ id: 0, text: message }])
};
_state.next(newState);
};
const remove = (id: number) => {
const currentState = _state.value;
const newState: AlertsStoreState = {
...currentState,
alerts: currentState.alerts.filter(a => a.id !== id)
};
_state.next(newState);
};
//
// START PUBLIC API
//
// Composable, to access state from vue's reactivity system.
export const useAlerts = () => {
const state = useObservable(_state);
return {
alerts: computed(() => state.value.alerts),
notify,
remove
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment