@@ -72,7 +72,7 @@ function useContainedStore(scope, registry, propsRef, check, override) {
72
72
storeState,
73
73
actions,
74
74
handlers,
75
- unsubscribe : storeState . subscribe ( ( ) => handlers . onUpdate ?. ( ) ) ,
75
+ unsubscribe : undefined ,
76
76
} ;
77
77
containedStores . set ( Store , containedStore ) ;
78
78
// Signal store is contained and ready now, so by the time
@@ -84,6 +84,7 @@ function useContainedStore(scope, registry, propsRef, check, override) {
84
84
} ,
85
85
[ containedStores , scope , registry , propsRef , check , override ]
86
86
) ;
87
+
87
88
return [ containedStores , getContainedStore ] ;
88
89
}
89
90
@@ -143,6 +144,21 @@ function createFunctionContainer({ displayName, override } = {}) {
143
144
) ;
144
145
} ) ;
145
146
}
147
+ // Every time we add/remove a contained store, we ensure we are subscribed to the updates
148
+ // as an effect to properly handle strict mode
149
+ useEffect ( ( ) => {
150
+ containedStores . forEach ( ( containedStore ) => {
151
+ if ( ! containedStore . unsubscribe ) {
152
+ const unsub = containedStore . storeState . subscribe ( ( ) =>
153
+ containedStore . handlers . onUpdate ?. ( )
154
+ ) ;
155
+ containedStore . unsubscribe = ( ) => {
156
+ unsub ( ) ;
157
+ containedStore . unsubscribe = undefined ;
158
+ } ;
159
+ }
160
+ } ) ;
161
+ } , [ containedStores , containedStores . size ] ) ;
146
162
147
163
// We support renderding "bootstrap" containers without children with override API
148
164
// so in this case we call getCS to initialize the store globally asap
@@ -157,7 +173,7 @@ function createFunctionContainer({ displayName, override } = {}) {
157
173
containedStores . forEach (
158
174
( { storeState, handlers, unsubscribe } , Store ) => {
159
175
// Detatch container from subscription
160
- unsubscribe ( ) ;
176
+ unsubscribe ?. ( ) ;
161
177
// Trigger a forced update on all subscribers as we opted out from context
162
178
// Some might have already re-rendered naturally, but we "force update" all anyway.
163
179
// This is sub-optimal as if there are other containers with the same
@@ -173,14 +189,14 @@ function createFunctionContainer({ displayName, override } = {}) {
173
189
) {
174
190
handlers . onDestroy ?. ( ) ;
175
191
// We only delete scoped stores, as global shall persist and local are auto-deleted
176
- if ( scope ) registry . deleteStore ( Store , scope ) ;
192
+ if ( ! isGlobal ) registry . deleteStore ( Store , scope ) ;
177
193
}
178
194
} ) ;
179
195
}
180
196
) ;
181
197
// no need to reset containedStores as the map is already bound to scope
182
198
} ;
183
- } , [ registry , scope , containedStores ] ) ;
199
+ } , [ registry , scope , isGlobal , containedStores ] ) ;
184
200
185
201
return < Context . Provider value = { api } > { children } </ Context . Provider > ;
186
202
}
0 commit comments