]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
feat: state hydration
authorEduardo San Martin Morote <posva13@gmail.com>
Tue, 14 Jan 2020 17:43:27 +0000 (18:43 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Mon, 20 Jan 2020 18:21:18 +0000 (19:21 +0100)
__tests__/store.spec.ts
src/store.ts

index e584b99039a06732d34a409b9c6cf37ff3a499c6..2defbd2ef17916faa5ae00419310aee0fd2dbf08 100644 (file)
@@ -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 = {
index 349950c6c4abf6777c3629656e86e1bac74bd5cf..a0c2f7b654b4006c8492319f7e48cd34ed201192 100644 (file)
@@ -57,10 +57,11 @@ export function buildStore<
 >(
   id: Id,
   buildState: () => S,
-  getters: G = {} as G
+  getters: G = {} as G,
+  initialState?: S | undefined
   // methods: Record<string | symbol, StoreMethod>
 ): CombinedStore<Id, S, G> {
-  const state: Ref<S> = ref(buildState())
+  const state: Ref<S> = ref(initialState || buildState())
 
   let isListening = true
   let subscriptions: SubscriptionCallback<S>[] = []
@@ -176,11 +177,8 @@ export function createStore<
 >(id: Id, buildState: () => S, getters: G = {} as G) {
   let store: CombinedStore<Id, S, G> | 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<Id, S>
+    initialStates: Record<Id, S> = {} as Record<Id, S>
   ): CombinedStore<Id, S, G> {
     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)
     }