From: Eduardo San Martin Morote Date: Mon, 13 Jan 2020 19:20:04 +0000 (+0100) Subject: feat: export types, support state hydration X-Git-Tag: 0.0.5~27 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=89996ed89bb793475ef17e6eaf427518931a56b5;p=thirdparty%2Fvuejs%2Fpinia.git feat: export types, support state hydration --- diff --git a/src/index.ts b/src/index.ts index 97b1efdc..7c7dc067 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,2 @@ -export { createStore } from './store' +export { createStore, CombinedStore } from './store' +export { StateTree, StoreGetter } from './types' diff --git a/src/store.ts b/src/store.ts index 9cabaef7..49d91cbc 100644 --- a/src/store.ts +++ b/src/store.ts @@ -148,13 +148,17 @@ export function buildStore< * be able to reset the store instance between requests on the server */ +const storesMap = new WeakMap< + object, + Record> +>() + /** * Creates a `useStore` function that retrieves the store instance * @param id id of the store we are creating * @param buildState function that returns a state * @param getters optional object of getters */ - export function createStore< Id extends string, S extends StateTree, @@ -162,10 +166,22 @@ export function createStore< >(id: Id, buildState: () => S, getters: G = {} as G) { let store: CombinedStore | undefined - return function useStore(forceNewStore = false): CombinedStore { - if (!store || forceNewStore) store = buildStore(id, buildState, getters) - - useStoreDevtools(store) + // 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( + req?: object | boolean, + initialStates?: Record + ): CombinedStore { + if (!req || typeof req === 'boolean') { + if (!store || req) store = buildStore(id, buildState, getters) + if (initialStates && initialStates[id]) store.state = initialStates[id] + useStoreDevtools(store) + } else { + let stores = storesMap.get(req) + if (!stores) storesMap.set(req, (stores = {})) + store = stores[id] + if (!store) stores[id] = store = buildStore(id, buildState, getters) + } return store }