Skip to content

Commit 5959e27

Browse files
m.berezinm.berezin
authored andcommitted
fix(react/createConsumer): Use WeakMap (instead of object) to store consumers
1 parent 0290af0 commit 5959e27

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed

src/react/createConsumer/createConsumer.spec.tsx

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ describe('createContext', () => {
1919

2020
const wait = (n: number) => new Promise((resolve) => setTimeout(resolve, n))
2121

22-
const getApp = () =>
22+
const getApp = (appName = 'test' + uniqueId()) =>
2323
createApp({
24-
name: 'test' + uniqueId(),
24+
name: appName,
2525
modules: [
2626
{
2727
name: 'test',
@@ -252,4 +252,21 @@ describe('createContext', () => {
252252
expect(Consumer1).not.toBe(Consumer2)
253253
expect(Consumer1).not.toBe(Consumer4)
254254
})
255+
256+
it('should create different components for applications with same name', () => {
257+
const app1 = getApp('test')
258+
const app2 = getApp('test')
259+
const app3 = getApp('test')
260+
261+
const Consumer1 = createConsumer(app1)
262+
const Consumer2 = createConsumer(app2)
263+
const Consumer3 = createConsumer(app1)
264+
const Consumer4 = createConsumer(app3)
265+
const Consumer5 = createConsumer(app1)
266+
267+
expect(Consumer1).toBe(Consumer3)
268+
expect(Consumer1).toBe(Consumer5)
269+
expect(Consumer1).not.toBe(Consumer2)
270+
expect(Consumer1).not.toBe(Consumer4)
271+
})
255272
})

src/react/createConsumer/createConsumer.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@ import { ConsumerProps } from './createConsumer.h'
2222
/**
2323
* @private
2424
*/
25-
const consumers: { [K: string]: ComponentClass<ConsumerProps<any, any, any, any, any>> } = {}
25+
26+
const consumers = new WeakMap<
27+
Stapp<any, any>,
28+
ComponentClass<ConsumerProps<any, any, any, any, any>>
29+
>()
2630

2731
/**
2832
* @private
@@ -41,13 +45,11 @@ const consumerPropTypes = {
4145
export const createConsumer = <State, Api>(
4246
app: Stapp<State, Api>
4347
): ComponentClass<ConsumerProps<State, Api, any, any, any>> => {
44-
if (consumers[app.name]) {
45-
return consumers[app.name]
48+
if (consumers.has(app)) {
49+
return consumers.get(app) as ComponentClass<ConsumerProps<any, any, any, any, any>>
4650
}
4751

48-
return (consumers[app.name] = class Consumer extends Component<
49-
ConsumerProps<State, Api, any, any, any>
50-
> {
52+
const consumer = class Consumer extends Component<ConsumerProps<State, Api, any, any, any>> {
5153
static propTypes = consumerPropTypes
5254

5355
subscription!: Subscription
@@ -112,5 +114,9 @@ export const createConsumer = <State, Api>(
112114
'Consumer'
113115
)
114116
}
115-
})
117+
}
118+
119+
consumers.set(app, consumer)
120+
121+
return consumer
116122
}

0 commit comments

Comments
 (0)