-import { createPinia, defineStore, mapStores, PiniaPlugin } from '../src'
+import {
+ createPinia,
+ defineStore,
+ mapGetters,
+ mapState,
+ mapStores,
+ PiniaPlugin,
+} from '../src'
import { createLocalVue, mount } from '@vue/test-utils'
import VueCompositionAPI, {
nextTick,
})
})
- // mapStores(useStore).main().$patch({ n: 20 })
+ it('mapGetters', () => {
+ expect(mapGetters).toBe(mapState)
+ })
+
+ describe('mapState', () => {
+ async function testComponent(
+ computedProperties: any,
+ template: string,
+ expectedText: string
+ ) {
+ const pinia = createPinia()
+ const Component = defineComponent({
+ template: `<p>${template}</p>`,
+ computed: {
+ ...computedProperties,
+ },
+ })
+
+ const wrapper = mount(Component, { localVue, pinia })
- const wrapper = mount(Component, { localVue, pinia })
- expect(wrapper.vm.main).toBeDefined()
- const store = useStore()
- expect(wrapper.text()).toBe('0 0')
- expect(fromStore).toHaveBeenCalledTimes(1)
+ expect(wrapper.text()).toBe(expectedText)
+ }
- store.n++
- await nextTick()
- expect(wrapper.text()).toBe('1 1')
- expect(fromStore).toHaveBeenCalledTimes(1)
+ it('array', async () => {
+ await testComponent(
+ mapState(useStore, ['n', 'a']),
+ `{{ n }} {{ a }}`,
+ `0 true`
+ )
+ })
+
+ it('getters', async () => {
+ await testComponent(
+ mapState(useStore, ['double', 'notA', 'a']),
+ `{{ a }} {{ notA }} {{ double }}`,
+ `true false 0`
+ )
+ })
})
})
-import { GenericStoreDefinition, Store, StoreDefinition } from './types'
+import {
+ GenericStoreDefinition,
+ Method,
+ StateTree,
+ Store,
+ StoreDefinition,
+} from './types'
type StoreObject<S> = S extends StoreDefinition<
infer Ids,
return reduced
}, {} as Spread<Stores>)
}
+
+type MapStateReturn<S extends StateTree, G> = {
+ [s in keyof S | keyof G]: () => Store<string, S, G, {}>
+}
+
+export function mapState<Id extends string, S extends StateTree, G, A>(
+ useStore: StoreDefinition<Id, S, G, A>,
+ keys: Array<keyof S | keyof G>
+): MapStateReturn<S, G> {
+ return keys.reduce((reduced, key) => {
+ reduced[key] = function () {
+ return useStore((this as any).$pinia)[key]
+ }
+ return reduced
+ }, {} as MapStateReturn<S, G>)
+}
+
+/**
+ * Alias for `mapState()`. You should use `mapState()` instead.
+ */
+export const mapGetters = mapState