Last active
July 13, 2022 19:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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