Skip to content

Commit

Permalink
fix: avoid reusing context between stores (#365)
Browse files Browse the repository at this point in the history
  • Loading branch information
ktsn committed Dec 22, 2020
1 parent 89fd9bc commit 30e5a36
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 15 deletions.
27 changes: 12 additions & 15 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,10 @@ function initGetters<
injectStore: (store) => {
const context = module.context(store)

if (!getters.hasOwnProperty('__ctx__')) {
Object.defineProperty(getters, '__ctx__', {
get: () => context,
})
}
Object.defineProperty(getters, '__ctx__', {
get: () => context,
configurable: true,
})

getters.$init(store)
},
Expand Down Expand Up @@ -365,11 +364,10 @@ function initMutations<
injectStore: (store) => {
const context = module.context(store)

if (!mutations.hasOwnProperty('__ctx__')) {
Object.defineProperty(mutations, '__ctx__', {
get: () => context,
})
}
Object.defineProperty(mutations, '__ctx__', {
get: () => context,
configurable: true,
})
},
}
}
Expand Down Expand Up @@ -430,11 +428,10 @@ function initActions<
injectStore: (store) => {
const context = module.context(store)

if (!actions.hasOwnProperty('__ctx__')) {
Object.defineProperty(actions, '__ctx__', {
get: () => context,
})
}
Object.defineProperty(actions, '__ctx__', {
get: () => context,
configurable: true,
})

actions.$init(store)
},
Expand Down
40 changes: 40 additions & 0 deletions test/module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,46 @@ describe('Module', () => {

expect(foo.context(store).getters.test).toBe(1)
})

it('does not access old store state via ctx', () => {
class FooState {
test: string | null = null
}

class FooMutations extends Mutations<FooState> {
update(value: string) {
this.state.test = value
}
}

class FooActions extends Actions<
FooState,
never,
FooMutations,
FooActions
> {
update(value: string) {
this.mutations.update(value)
}
}

const root = new Module({
state: FooState,
mutations: FooMutations,
actions: FooActions,
})

const storeA = createStore(root)
expect(storeA.state.test).toBe(null)
storeA.dispatch('update', 'a')
expect(storeA.state.test).toBe('a')

const storeB = createStore(root)
expect(storeB.state.test).toBe(null)
storeB.dispatch('update', 'b')
expect(storeA.state.test).toBe('a')
expect(storeB.state.test).toBe('b')
})
})

it("can be used in other module's action", () => {
Expand Down

0 comments on commit 30e5a36

Please sign in to comment.