From: Eduardo San Martin Morote Date: Tue, 14 Jan 2020 17:43:27 +0000 (+0100) Subject: feat: state hydration X-Git-Tag: 0.0.5~22 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=db722474fceb5a9090136e2fdf4a706b3dd22d88;p=thirdparty%2Fvuejs%2Fpinia.git feat: state hydration --- diff --git a/__tests__/store.spec.ts b/__tests__/store.spec.ts index e584b990..2defbd2e 100644 --- a/__tests__/store.spec.ts +++ b/__tests__/store.spec.ts @@ -1,7 +1,7 @@ import { createStore, setActiveReq } from '../src' describe('Store', () => { - const useStore = () => { + const useStore = (...args: any[]) => { // create a new store setActiveReq({}) return createStore('main', () => ({ @@ -10,7 +10,7 @@ describe('Store', () => { foo: 'foo', a: { b: 'string' }, }, - }))() + }))(...args) } it('sets the initial state', () => { @@ -24,6 +24,25 @@ describe('Store', () => { }) }) + it('can hydrate the state', () => { + const store = useStore({ + main: { + a: false, + nested: { + foo: 'bar', + a: { b: 'string' }, + }, + }, + }) + expect(store.state).toEqual({ + a: false, + nested: { + foo: 'bar', + a: { b: 'string' }, + }, + }) + }) + it('can replace its state', () => { const store = useStore() store.state = { diff --git a/src/store.ts b/src/store.ts index 349950c6..a0c2f7b6 100644 --- a/src/store.ts +++ b/src/store.ts @@ -57,10 +57,11 @@ export function buildStore< >( id: Id, buildState: () => S, - getters: G = {} as G + getters: G = {} as G, + initialState?: S | undefined // methods: Record ): CombinedStore { - const state: Ref = ref(buildState()) + const state: Ref = ref(initialState || buildState()) let isListening = true let subscriptions: SubscriptionCallback[] = [] @@ -176,11 +177,8 @@ export function createStore< >(id: Id, buildState: () => S, getters: G = {} as G) { let store: CombinedStore | undefined - // TODO: do we really need the boolean version for SSR? Using the request would be better - // as it allows async code like pending requests to use the correct store version. return function useStore( - force?: boolean, - initialStates?: Record + initialStates: Record = {} as Record ): CombinedStore { const req = getActiveReq() let stores = storesMap.get(req) @@ -188,9 +186,12 @@ export function createStore< store = stores[id] if (!store) { - stores[id] = store = buildStore(id, buildState, getters) - // hydrate state - if (initialStates && initialStates[id]) store.state = initialStates[id] + stores[id] = store = buildStore( + id, + buildState, + getters, + initialStates[id] + ) if (isClient) useStoreDevtools(store) }