Skip to content

Commit

Permalink
feat: allow passing the req to useStore
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jan 20, 2020
1 parent 5e262da commit f250622
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
16 changes: 16 additions & 0 deletions __tests__/actions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,20 @@ describe('Store', () => {
// a different instance of b store was used
expect(bStore.state.b).toBe('c')
})

it('can force the req', () => {
const req1 = {}
const req2 = {}
const aStore = useA(req1)

let bStore = useB(req2)
bStore.state.b = 'c'

aStore.swap()
expect(aStore.state.a).toBe('b')
// a different instance of b store was used
expect(bStore.state.b).toBe('c')
bStore = useB(req1)
expect(bStore.state.b).toBe('a')
})
})
7 changes: 4 additions & 3 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export function buildStore<
* be able to reset the store instance between requests on the server
*/

const storesMap = new WeakMap<
export const storesMap = new WeakMap<
NonNullObject,
Record<string, Store<any, any, any, any>>
>()
Expand Down Expand Up @@ -263,7 +263,8 @@ export function createStore<
}) {
const { id, state, getters, actions } = options

return function useStore(): Store<Id, S, G, A> {
return function useStore(reqKey?: object): Store<Id, S, G, A> {
if (reqKey) setActiveReq(reqKey)
const req = getActiveReq()
let stores = storesMap.get(req)
if (!stores) storesMap.set(req, (stores = {}))
Expand All @@ -278,7 +279,7 @@ export function createStore<
getInitialState(id)
)
// save a reference to the initial state
// TODO: this implies that replacing the store cannot be done by the user because we are relying on the object reference
// TODO: this implies that replacing the store cannot be done by the user on the server
setInitialState(store)
if (isClient) useStoreDevtools(store)
}
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"allowJs": true,
"target": "esnext",
"module": "esnext",
"noEmit": true,
Expand All @@ -12,5 +13,5 @@
"rootDir": ".",
"baseUrl": "."
},
"include": ["src/**/*.ts", "__tests__/**/**.ts"]
"include": ["src/**/*.ts", "nuxt/*.js", "__tests__/**/**.ts"]
}

0 comments on commit f250622

Please sign in to comment.