-
Notifications
You must be signed in to change notification settings - Fork 73
/
Onyx.js
1630 lines (1435 loc) · 64.4 KB
/
Onyx.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-continue */
import {deepEqual} from 'fast-equals';
import _ from 'underscore';
import * as Logger from './Logger';
import cache from './OnyxCache';
import * as Str from './Str';
import createDeferredTask from './createDeferredTask';
import * as PerformanceUtils from './metrics/PerformanceUtils';
import Storage from './storage';
import utils from './utils';
import unstable_batchedUpdates from './batch';
// Method constants
const METHOD = {
SET: 'set',
MERGE: 'merge',
MERGE_COLLECTION: 'mergecollection',
MULTI_SET: 'multiset',
CLEAR: 'clear',
};
// Key/value store of Onyx key and arrays of values to merge
const mergeQueue = {};
const mergeQueuePromise = {};
// Keeps track of the last connectionID that was used so we can keep incrementing it
let lastConnectionID = 0;
// Holds a mapping of all the react components that want their state subscribed to a store key
const callbackToStateMapping = {};
// Keeps a copy of the values of the onyx collection keys as a map for faster lookups
let onyxCollectionKeyMap = new Map();
// Holds a list of keys that have been directly subscribed to or recently modified from least to most recent
let recentlyAccessedKeys = [];
// Holds a list of keys that are safe to remove when we reach max storage. If a key does not match with
// whatever appears in this list it will NEVER be a candidate for eviction.
let evictionAllowList = [];
// Holds a map of keys and connectionID arrays whose keys will never be automatically evicted as
// long as we have at least one subscriber that returns false for the canEvict property.
const evictionBlocklist = {};
// Optional user-provided key value states set when Onyx initializes or clears
let defaultKeyStates = {};
// Connections can be made before `Onyx.init`. They would wait for this task before resolving
const deferredInitTask = createDeferredTask();
let batchUpdatesPromise = null;
let batchUpdatesQueue = [];
/**
* We are batching together onyx updates. This helps with use cases where we schedule onyx updates after each other.
* This happens for example in the Onyx.update function, where we process API responses that might contain a lot of
* update operations. Instead of calling the subscribers for each update operation, we batch them together which will
* cause react to schedule the updates at once instead of after each other. This is mainly a performance optimization.
* @returns {Promise}
*/
function maybeFlushBatchUpdates() {
if (batchUpdatesPromise) {
return batchUpdatesPromise;
}
batchUpdatesPromise = new Promise((resolve) => {
/* We use (setTimeout, 0) here which should be called once native module calls are flushed (usually at the end of the frame)
* We may investigate if (setTimeout, 1) (which in React Native is equal to requestAnimationFrame) works even better
* then the batch will be flushed on next frame.
*/
setTimeout(() => {
const updatesCopy = batchUpdatesQueue;
batchUpdatesQueue = [];
batchUpdatesPromise = null;
unstable_batchedUpdates(() => {
updatesCopy.forEach((applyUpdates) => {
applyUpdates();
});
});
resolve();
}, 0);
});
return batchUpdatesPromise;
}
function batchUpdates(updates) {
batchUpdatesQueue.push(updates);
return maybeFlushBatchUpdates();
}
/**
* Uses a selector function to return a simplified version of sourceData
* @param {Mixed} sourceData
* @param {Function} selector Function that takes sourceData and returns a simplified version of it
* @param {Object} [withOnyxInstanceState]
* @returns {Mixed}
*/
const getSubsetOfData = (sourceData, selector, withOnyxInstanceState) => selector(sourceData, withOnyxInstanceState);
/**
* Takes a collection of items (eg. {testKey_1:{a:'a'}, testKey_2:{b:'b'}})
* and runs it through a reducer function to return a subset of the data according to a selector.
* The resulting collection will only contain items that are returned by the selector.
* @param {Object} collection
* @param {String|Function} selector (see method docs for getSubsetOfData() for full details)
* @param {Object} [withOnyxInstanceState]
* @returns {Object}
*/
const reduceCollectionWithSelector = (collection, selector, withOnyxInstanceState) => _.reduce(collection, (finalCollection, item, key) => {
// eslint-disable-next-line no-param-reassign
finalCollection[key] = getSubsetOfData(item, selector, withOnyxInstanceState);
return finalCollection;
}, {});
/**
* Get some data from the store
*
* @private
* @param {string} key
* @returns {Promise<*>}
*/
function get(key) {
// When we already have the value in cache - resolve right away
if (cache.hasCacheForKey(key)) {
return Promise.resolve(cache.getValue(key));
}
const taskName = `get:${key}`;
// When a value retrieving task for this key is still running hook to it
if (cache.hasPendingTask(taskName)) {
return cache.getTaskPromise(taskName);
}
// Otherwise retrieve the value from storage and capture a promise to aid concurrent usages
const promise = Storage.getItem(key)
.then((val) => {
cache.set(key, val);
return val;
})
.catch(err => Logger.logInfo(`Unable to get item from persistent storage. Key: ${key} Error: ${err}`));
return cache.captureTask(taskName, promise);
}
/**
* Returns current key names stored in persisted storage
* @private
* @returns {Promise<string[]>}
*/
function getAllKeys() {
// When we've already read stored keys, resolve right away
const storedKeys = cache.getAllKeys();
if (storedKeys.length > 0) {
return Promise.resolve(storedKeys);
}
const taskName = 'getAllKeys';
// When a value retrieving task for all keys is still running hook to it
if (cache.hasPendingTask(taskName)) {
return cache.getTaskPromise(taskName);
}
// Otherwise retrieve the keys from storage and capture a promise to aid concurrent usages
const promise = Storage.getAllKeys()
.then((keys) => {
_.each(keys, key => cache.addKey(key));
return keys;
});
return cache.captureTask(taskName, promise);
}
/**
* Checks to see if the a subscriber's supplied key
* is associated with a collection of keys.
*
* @private
* @param {String} key
* @returns {Boolean}
*/
function isCollectionKey(key) {
return onyxCollectionKeyMap.has(key);
}
/**
* @param {String} collectionKey
* @param {String} key
* @returns {Boolean}
*/
function isCollectionMemberKey(collectionKey, key) {
return Str.startsWith(key, collectionKey) && key.length > collectionKey.length;
}
/**
* Checks to see if a provided key is the exact configured key of our connected subscriber
* or if the provided key is a collection member key (in case our configured key is a "collection key")
*
* @private
* @param {String} configKey
* @param {String} key
* @return {Boolean}
*/
function isKeyMatch(configKey, key) {
return isCollectionKey(configKey)
? Str.startsWith(key, configKey)
: configKey === key;
}
/**
* Checks to see if this key has been flagged as
* safe for removal.
*
* @private
* @param {String} testKey
* @returns {Boolean}
*/
function isSafeEvictionKey(testKey) {
return _.some(evictionAllowList, key => isKeyMatch(key, testKey));
}
/**
* Tries to get a value from the cache. If the value is not present in cache it will return the default value or undefined.
* If the requested key is a collection, it will return an object with all the collection members.
*
* @param {String} key
* @param {Object} mapping
* @returns {Mixed}
*/
function tryGetCachedValue(key, mapping = {}) {
let val = cache.getValue(key);
if (isCollectionKey(key)) {
const allCacheKeys = cache.getAllKeys();
// It is possible we haven't loaded all keys yet so we do not know if the
// collection actually exists.
if (allCacheKeys.length === 0) {
return;
}
const matchingKeys = _.filter(allCacheKeys, k => k.startsWith(key));
const values = _.reduce(matchingKeys, (finalObject, matchedKey) => {
const cachedValue = cache.getValue(matchedKey);
if (cachedValue) {
// This is permissible because we're in the process of constructing the final object in a reduce function.
// eslint-disable-next-line no-param-reassign
finalObject[matchedKey] = cachedValue;
}
return finalObject;
}, {});
val = values;
}
if (mapping.selector) {
const state = mapping.withOnyxInstance ? mapping.withOnyxInstance.state : undefined;
if (isCollectionKey(key)) {
return reduceCollectionWithSelector(val, mapping.selector, state);
}
return getSubsetOfData(val, mapping.selector, state);
}
return val;
}
/**
* Remove a key from the recently accessed key list.
*
* @private
* @param {String} key
*/
function removeLastAccessedKey(key) {
recentlyAccessedKeys = _.without(recentlyAccessedKeys, key);
}
/**
* Add a key to the list of recently accessed keys. The least
* recently accessed key should be at the head and the most
* recently accessed key at the tail.
*
* @private
* @param {String} key
*/
function addLastAccessedKey(key) {
// Only specific keys belong in this list since we cannot remove an entire collection.
if (isCollectionKey(key) || !isSafeEvictionKey(key)) {
return;
}
removeLastAccessedKey(key);
recentlyAccessedKeys.push(key);
}
/**
* Removes a key previously added to this list
* which will enable it to be deleted again.
*
* @private
* @param {String} key
* @param {Number} connectionID
*/
function removeFromEvictionBlockList(key, connectionID) {
evictionBlocklist[key] = _.without(evictionBlocklist[key] || [], connectionID);
// Remove the key if there are no more subscribers
if (evictionBlocklist[key].length === 0) {
delete evictionBlocklist[key];
}
}
/**
* Keys added to this list can never be deleted.
*
* @private
* @param {String} key
* @param {Number} connectionID
*/
function addToEvictionBlockList(key, connectionID) {
removeFromEvictionBlockList(key, connectionID);
if (!evictionBlocklist[key]) {
evictionBlocklist[key] = [];
}
evictionBlocklist[key].push(connectionID);
}
/**
* Take all the keys that are safe to evict and add them to
* the recently accessed list when initializing the app. This
* enables keys that have not recently been accessed to be
* removed.
*
* @private
* @returns {Promise}
*/
function addAllSafeEvictionKeysToRecentlyAccessedList() {
return getAllKeys()
.then((keys) => {
_.each(evictionAllowList, (safeEvictionKey) => {
_.each(keys, (key) => {
if (!isKeyMatch(safeEvictionKey, key)) {
return;
}
addLastAccessedKey(key);
});
});
});
}
/**
* @private
* @param {String} collectionKey
* @returns {Object}
*/
function getCachedCollection(collectionKey) {
const collectionMemberKeys = _.filter(cache.getAllKeys(), (
storedKey => isCollectionMemberKey(collectionKey, storedKey)
));
return _.reduce(collectionMemberKeys, (prev, curr) => {
const cachedValue = cache.getValue(curr);
if (!cachedValue) {
return prev;
}
// eslint-disable-next-line no-param-reassign
prev[curr] = cachedValue;
return prev;
}, {});
}
/**
* When a collection of keys change, search for any callbacks matching the collection key and trigger those callbacks
*
* @private
* @param {String} collectionKey
* @param {Object} partialCollection - a partial collection of grouped member keys
* @param {boolean} [notifyRegularSubscibers=true]
* @param {boolean} [notifyWithOnyxSubscibers=true]
*/
function keysChanged(collectionKey, partialCollection, notifyRegularSubscibers = true, notifyWithOnyxSubscibers = true) {
// We are iterating over all subscribers similar to keyChanged(). However, we are looking for subscribers who are subscribing to either a collection key or
// individual collection key member for the collection that is being updated. It is important to note that the collection parameter cane be a PARTIAL collection
// and does not represent all of the combined keys and values for a collection key. It is just the "new" data that was merged in via mergeCollection().
const stateMappingKeys = _.keys(callbackToStateMapping);
for (let i = 0; i < stateMappingKeys.length; i++) {
const subscriber = callbackToStateMapping[stateMappingKeys[i]];
if (!subscriber) {
continue;
}
// Skip iteration if we do not have a collection key or a collection member key on this subscriber
if (!Str.startsWith(subscriber.key, collectionKey)) {
continue;
}
/**
* e.g. Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT, callback: ...});
*/
const isSubscribedToCollectionKey = subscriber.key === collectionKey;
/**
* e.g. Onyx.connect({key: `${ONYXKEYS.COLLECTION.REPORT}{reportID}`, callback: ...});
*/
const isSubscribedToCollectionMemberKey = isCollectionMemberKey(collectionKey, subscriber.key);
// We prepare the "cached collection" which is the entire collection + the new partial data that
// was merged in via mergeCollection().
const cachedCollection = getCachedCollection(collectionKey);
// Regular Onyx.connect() subscriber found.
if (_.isFunction(subscriber.callback)) {
if (!notifyRegularSubscibers) {
continue;
}
// If they are subscribed to the collection key and using waitForCollectionCallback then we'll
// send the whole cached collection.
if (isSubscribedToCollectionKey) {
if (subscriber.waitForCollectionCallback) {
subscriber.callback(cachedCollection);
continue;
}
// If they are not using waitForCollectionCallback then we notify the subscriber with
// the new merged data but only for any keys in the partial collection.
const dataKeys = _.keys(partialCollection);
for (let j = 0; j < dataKeys.length; j++) {
const dataKey = dataKeys[j];
subscriber.callback(cachedCollection[dataKey], dataKey);
}
continue;
}
// And if the subscriber is specifically only tracking a particular collection member key then we will
// notify them with the cached data for that key only.
if (isSubscribedToCollectionMemberKey) {
subscriber.callback(cachedCollection[subscriber.key], subscriber.key);
continue;
}
continue;
}
// React component subscriber found.
if (subscriber.withOnyxInstance) {
if (!notifyWithOnyxSubscibers) {
continue;
}
// We are subscribed to a collection key so we must update the data in state with the new
// collection member key values from the partial update.
if (isSubscribedToCollectionKey) {
// If the subscriber has a selector, then the component's state must only be updated with the data
// returned by the selector.
if (subscriber.selector) {
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const previousData = prevState[subscriber.statePropertyName];
const newData = reduceCollectionWithSelector(cachedCollection, subscriber.selector, subscriber.withOnyxInstance.state);
if (!deepEqual(previousData, newData)) {
return {
[subscriber.statePropertyName]: newData,
};
}
return null;
});
continue;
}
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const finalCollection = _.clone(prevState[subscriber.statePropertyName] || {});
const dataKeys = _.keys(partialCollection);
for (let j = 0; j < dataKeys.length; j++) {
const dataKey = dataKeys[j];
finalCollection[dataKey] = cachedCollection[dataKey];
}
PerformanceUtils.logSetStateCall(subscriber, prevState[subscriber.statePropertyName], finalCollection, 'keysChanged', collectionKey);
return {
[subscriber.statePropertyName]: finalCollection,
};
});
continue;
}
// If a React component is only interested in a single key then we can set the cached value directly to the state name.
if (isSubscribedToCollectionMemberKey) {
// However, we only want to update this subscriber if the partial data contains a change.
// Otherwise, we would update them with a value they already have and trigger an unnecessary re-render.
const dataFromCollection = partialCollection[subscriber.key];
if (_.isUndefined(dataFromCollection)) {
continue;
}
// If the subscriber has a selector, then the component's state must only be updated with the data
// returned by the selector and the state should only change when the subset of data changes from what
// it was previously.
if (subscriber.selector) {
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const prevData = prevState[subscriber.statePropertyName];
const newData = getSubsetOfData(cachedCollection[subscriber.key], subscriber.selector, subscriber.withOnyxInstance.state);
if (!deepEqual(prevData, newData)) {
PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keysChanged', collectionKey);
return {
[subscriber.statePropertyName]: newData,
};
}
return null;
});
continue;
}
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const data = cachedCollection[subscriber.key];
const previousData = prevState[subscriber.statePropertyName];
// Avoids triggering unnecessary re-renders when feeding empty objects
if (utils.areObjectsEmpty(data, previousData)) {
return null;
}
if (data === previousData) {
return null;
}
PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keysChanged', collectionKey);
return {
[subscriber.statePropertyName]: data,
};
});
}
}
}
}
/**
* When a key change happens, search for any callbacks matching the key or collection key and trigger those callbacks
*
* @example
* keyChanged(key, value, subscriber => subscriber.initWithStoredValues === false)
*
* @private
* @param {String} key
* @param {*} data
* @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated
* @param {boolean} [notifyRegularSubscibers=true]
* @param {boolean} [notifyWithOnyxSubscibers=true]
*/
function keyChanged(key, data, canUpdateSubscriber, notifyRegularSubscibers = true, notifyWithOnyxSubscibers = true) {
// Add or remove this key from the recentlyAccessedKeys lists
if (!_.isNull(data)) {
addLastAccessedKey(key);
} else {
removeLastAccessedKey(key);
}
// We are iterating over all subscribers to see if they are interested in the key that has just changed. If the subscriber's key is a collection key then we will
// notify them if the key that changed is a collection member. Or if it is a regular key notify them when there is an exact match. Depending on whether the subscriber
// was connected via withOnyx we will call setState() directly on the withOnyx instance. If it is a regular connection we will pass the data to the provided callback.
const stateMappingKeys = _.keys(callbackToStateMapping);
for (let i = 0; i < stateMappingKeys.length; i++) {
const subscriber = callbackToStateMapping[stateMappingKeys[i]];
if (!subscriber || !isKeyMatch(subscriber.key, key) || (_.isFunction(canUpdateSubscriber) && !canUpdateSubscriber(subscriber))) {
continue;
}
// Subscriber is a regular call to connect() and provided a callback
if (_.isFunction(subscriber.callback)) {
if (!notifyRegularSubscibers) {
continue;
}
if (isCollectionKey(subscriber.key) && subscriber.waitForCollectionCallback) {
const cachedCollection = getCachedCollection(subscriber.key);
cachedCollection[key] = data;
subscriber.callback(cachedCollection);
continue;
}
subscriber.callback(data, key);
continue;
}
// Subscriber connected via withOnyx() HOC
if (subscriber.withOnyxInstance) {
if (!notifyWithOnyxSubscibers) {
continue;
}
// Check if we are subscribing to a collection key and overwrite the collection member key value in state
if (isCollectionKey(subscriber.key)) {
// If the subscriber has a selector, then the consumer of this data must only be given the data
// returned by the selector and only when the selected data has changed.
if (subscriber.selector) {
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const prevData = prevState[subscriber.statePropertyName];
const newData = {
[key]: getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state),
};
const prevDataWithNewData = {
...prevData,
...newData,
};
if (!deepEqual(prevData, prevDataWithNewData)) {
PerformanceUtils.logSetStateCall(subscriber, prevData, newData, 'keyChanged', key);
return {
[subscriber.statePropertyName]: prevDataWithNewData,
};
}
return null;
});
continue;
}
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const collection = prevState[subscriber.statePropertyName] || {};
const newCollection = {
...collection,
[key]: data,
};
PerformanceUtils.logSetStateCall(subscriber, collection, newCollection, 'keyChanged', key);
return {
[subscriber.statePropertyName]: newCollection,
};
});
continue;
}
// If the subscriber has a selector, then the component's state must only be updated with the data
// returned by the selector and only if the selected data has changed.
if (subscriber.selector) {
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const previousValue = getSubsetOfData(prevState[subscriber.statePropertyName], subscriber.selector, subscriber.withOnyxInstance.state);
const newValue = getSubsetOfData(data, subscriber.selector, subscriber.withOnyxInstance.state);
if (!deepEqual(previousValue, newValue)) {
return {
[subscriber.statePropertyName]: newValue,
};
}
return null;
});
continue;
}
// If we did not match on a collection key then we just set the new data to the state property
subscriber.withOnyxInstance.setStateProxy((prevState) => {
const previousData = prevState[subscriber.statePropertyName];
// Avoids triggering unnecessary re-renders when feeding empty objects
if (utils.areObjectsEmpty(data, previousData)) {
return null;
}
if (previousData === data) {
return null;
}
PerformanceUtils.logSetStateCall(subscriber, previousData, data, 'keyChanged', key);
return {
[subscriber.statePropertyName]: data,
};
});
continue;
}
console.error('Warning: Found a matching subscriber to a key that changed, but no callback or withOnyxInstance could be found.');
}
}
/**
* Sends the data obtained from the keys to the connection. It either:
* - sets state on the withOnyxInstances
* - triggers the callback function
*
* @private
* @param {Object} mapping
* @param {Object} [mapping.withOnyxInstance]
* @param {String} [mapping.statePropertyName]
* @param {Function} [mapping.callback]
* @param {String} [mapping.selector]
* @param {*|null} val
* @param {String|undefined} matchedKey
* @param {Boolean} isBatched
*/
function sendDataToConnection(mapping, val, matchedKey, isBatched) {
// If the mapping no longer exists then we should not send any data.
// This means our subscriber disconnected or withOnyx wrapped component unmounted.
if (!callbackToStateMapping[mapping.connectionID]) {
return;
}
if (mapping.withOnyxInstance) {
let newData = val;
// If the mapping has a selector, then the component's state must only be updated with the data
// returned by the selector.
if (mapping.selector) {
if (isCollectionKey(mapping.key)) {
newData = reduceCollectionWithSelector(val, mapping.selector, mapping.withOnyxInstance.state);
} else {
newData = getSubsetOfData(val, mapping.selector, mapping.withOnyxInstance.state);
}
}
PerformanceUtils.logSetStateCall(mapping, null, newData, 'sendDataToConnection');
if (isBatched) {
batchUpdates(() => {
mapping.withOnyxInstance.setWithOnyxState(mapping.statePropertyName, newData);
});
} else {
mapping.withOnyxInstance.setWithOnyxState(mapping.statePropertyName, newData);
}
return;
}
if (_.isFunction(mapping.callback)) {
mapping.callback(val, matchedKey);
}
}
/**
* We check to see if this key is flagged as safe for eviction and add it to the recentlyAccessedKeys list so that when we
* run out of storage the least recently accessed key can be removed.
*
* @private
* @param {Object} mapping
*/
function addKeyToRecentlyAccessedIfNeeded(mapping) {
if (!isSafeEvictionKey(mapping.key)) {
return;
}
// Try to free some cache whenever we connect to a safe eviction key
cache.removeLeastRecentlyUsedKeys();
if (mapping.withOnyxInstance && !isCollectionKey(mapping.key)) {
// All React components subscribing to a key flagged as a safe eviction key must implement the canEvict property.
if (_.isUndefined(mapping.canEvict)) {
throw new Error(
`Cannot subscribe to safe eviction key '${mapping.key}' without providing a canEvict value.`,
);
}
addLastAccessedKey(mapping.key);
}
}
/**
* Gets the data for a given an array of matching keys, combines them into an object, and sends the result back to the subscriber.
*
* @private
* @param {Array} matchingKeys
* @param {Object} mapping
*/
function getCollectionDataAndSendAsObject(matchingKeys, mapping) {
Promise.all(_.map(matchingKeys, key => get(key)))
.then(values => _.reduce(values, (finalObject, value, i) => {
// eslint-disable-next-line no-param-reassign
finalObject[matchingKeys[i]] = value;
return finalObject;
}, {}))
.then(val => sendDataToConnection(mapping, val, undefined, true));
}
/**
* Subscribes a react component's state directly to a store key
*
* @example
* const connectionID = Onyx.connect({
* key: ONYXKEYS.SESSION,
* callback: onSessionChange,
* });
*
* @param {Object} mapping the mapping information to connect Onyx to the components state
* @param {String} mapping.key ONYXKEY to subscribe to
* @param {String} [mapping.statePropertyName] the name of the property in the state to connect the data to
* @param {Object} [mapping.withOnyxInstance] whose setState() method will be called with any changed data
* This is used by React components to connect to Onyx
* @param {Function} [mapping.callback] a method that will be called with changed data
* This is used by any non-React code to connect to Onyx
* @param {Boolean} [mapping.initWithStoredValues] If set to false, then no data will be prefilled into the
* component
* @param {Boolean} [mapping.waitForCollectionCallback] If set to true, it will return the entire collection to the callback as a single object
* @param {Function} [mapping.selector] THIS PARAM IS ONLY USED WITH withOnyx(). If included, this will be used to subscribe to a subset of an Onyx key's data.
* The sourceData and withOnyx state are passed to the selector and should return the simplified data. Using this setting on `withOnyx` can have very positive
* performance benefits because the component will only re-render when the subset of data changes. Otherwise, any change of data on any property would normally
* cause the component to re-render (and that can be expensive from a performance standpoint).
* @param {String | Number | Boolean | Object} [mapping.initialValue] THIS PARAM IS ONLY USED WITH withOnyx().
* If included, this will be passed to the component so that something can be rendered while data is being fetched from the DB.
* Note that it will not cause the component to have the loading prop set to true. |
* @returns {Number} an ID to use when calling disconnect
*/
function connect(mapping) {
const connectionID = lastConnectionID++;
callbackToStateMapping[connectionID] = mapping;
callbackToStateMapping[connectionID].connectionID = connectionID;
if (mapping.initWithStoredValues === false) {
return connectionID;
}
// Commit connection only after init passes
deferredInitTask.promise
.then(() => addKeyToRecentlyAccessedIfNeeded(mapping))
.then(() => {
// Performance improvement
// If the mapping is connected to an onyx key that is not a collection
// we can skip the call to getAllKeys() and return an array with a single item
if (Boolean(mapping.key)
&& typeof mapping.key === 'string'
&& !(mapping.key.endsWith('_'))
&& cache.storageKeys.has(mapping.key)
) {
return [mapping.key];
}
return getAllKeys();
})
.then((keys) => {
// We search all the keys in storage to see if any are a "match" for the subscriber we are connecting so that we
// can send data back to the subscriber. Note that multiple keys can match as a subscriber could either be
// subscribed to a "collection key" or a single key.
const matchingKeys = _.filter(keys, key => isKeyMatch(mapping.key, key));
// If the key being connected to does not exist we initialize the value with null. For subscribers that connected
// directly via connect() they will simply get a null value sent to them without any information about which key matched
// since there are none matched. In withOnyx() we wait for all connected keys to return a value before rendering the child
// component. This null value will be filtered out so that the connected component can utilize defaultProps.
if (matchingKeys.length === 0) {
if (mapping.key && !isCollectionKey(mapping.key)) {
cache.set(mapping.key, null);
}
// Here we cannot use batching because the null value is expected to be set immediately for default props
// or they will be undefined.
sendDataToConnection(mapping, null, undefined, false);
return;
}
// When using a callback subscriber we will either trigger the provided callback for each key we find or combine all values
// into an object and just make a single call. The latter behavior is enabled by providing a waitForCollectionCallback key
// combined with a subscription to a collection key.
if (_.isFunction(mapping.callback)) {
if (isCollectionKey(mapping.key)) {
if (mapping.waitForCollectionCallback) {
getCollectionDataAndSendAsObject(matchingKeys, mapping);
return;
}
// We did not opt into using waitForCollectionCallback mode so the callback is called for every matching key.
for (let i = 0; i < matchingKeys.length; i++) {
get(matchingKeys[i]).then(val => sendDataToConnection(mapping, val, matchingKeys[i], true));
}
return;
}
// If we are not subscribed to a collection key then there's only a single key to send an update for.
get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key, true));
return;
}
// If we have a withOnyxInstance that means a React component has subscribed via the withOnyx() HOC and we need to
// group collection key member data into an object.
if (mapping.withOnyxInstance) {
if (isCollectionKey(mapping.key)) {
getCollectionDataAndSendAsObject(matchingKeys, mapping);
return;
}
// If the subscriber is not using a collection key then we just send a single value back to the subscriber
get(mapping.key).then(val => sendDataToConnection(mapping, val, mapping.key, true));
return;
}
console.error('Warning: Onyx.connect() was found without a callback or withOnyxInstance');
});
// The connectionID is returned back to the caller so that it can be used to clean up the connection when it's no longer needed
// by calling Onyx.disconnect(connectionID).
return connectionID;
}
/**
* Remove the listener for a react component
* @example
* Onyx.disconnect(connectionID);
*
* @param {Number} connectionID unique id returned by call to Onyx.connect()
* @param {String} [keyToRemoveFromEvictionBlocklist]
*/
function disconnect(connectionID, keyToRemoveFromEvictionBlocklist) {
if (!callbackToStateMapping[connectionID]) {
return;
}
// Remove this key from the eviction block list as we are no longer
// subscribing to it and it should be safe to delete again
if (keyToRemoveFromEvictionBlocklist) {
removeFromEvictionBlockList(keyToRemoveFromEvictionBlocklist, connectionID);
}
delete callbackToStateMapping[connectionID];
}
/**
* Schedules an update that will be appended to the macro task queue (so it doesn't update the subscribers immediately).
*
* @example
* scheduleSubscriberUpdate(key, value, subscriber => subscriber.initWithStoredValues === false)
*
* @param {String} key
* @param {*} value
* @param {Function} [canUpdateSubscriber] only subscribers that pass this truth test will be updated
* @returns {Promise}
*/
function scheduleSubscriberUpdate(key, value, canUpdateSubscriber) {
const promise = Promise.resolve().then(() => keyChanged(key, value, canUpdateSubscriber, true, false));
batchUpdates(() => keyChanged(key, value, canUpdateSubscriber, false, true));
return Promise.all([maybeFlushBatchUpdates(), promise]);
}
/**
* This method is similar to notifySubscribersOnNextTick but it is built for working specifically with collections
* so that keysChanged() is triggered for the collection and not keyChanged(). If this was not done, then the
* subscriber callbacks receive the data in a different format than they normally expect and it breaks code.
*
* @param {String} key
* @param {*} value
* @returns {Promise}
*/
function scheduleNotifyCollectionSubscribers(key, value) {
const promise = Promise.resolve().then(() => keysChanged(key, value, true, false));
batchUpdates(() => keysChanged(key, value, false, true));
return Promise.all([maybeFlushBatchUpdates(), promise]);
}
/**
* Remove a key from Onyx and update the subscribers
*
* @private
* @param {String} key
* @return {Promise}
*/
function remove(key) {
cache.drop(key);
scheduleSubscriberUpdate(key, null);
return Storage.removeItem(key);
}
/**
* @private
* @returns {Promise<void>}
*/
function reportStorageQuota() {
return Storage.getDatabaseSize()
.then(({bytesUsed, bytesRemaining}) => {
Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}`);
})
.catch((dbSizeError) => {
Logger.logAlert(`Unable to get database size. Error: ${dbSizeError}`);
});
}
/**
* If we fail to set or merge we must handle this by
* evicting some data from Onyx and then retrying to do
* whatever it is we attempted to do.
*
* @private
* @param {Error} error
* @param {Function} onyxMethod
* @param {...any} args
* @return {Promise}
*/
function evictStorageAndRetry(error, onyxMethod, ...args) {
Logger.logInfo(`Failed to save to storage. Error: ${error}. onyxMethod: ${onyxMethod.name}`);
if (error && Str.startsWith(error.message, 'Failed to execute \'put\' on \'IDBObjectStore\'')) {
Logger.logAlert('Attempted to set invalid data set in Onyx. Please ensure all data is serializable.');
throw error;
}
// Find the first key that we can remove that has no subscribers in our blocklist
const keyForRemoval = _.find(recentlyAccessedKeys, key => !evictionBlocklist[key]);
if (!keyForRemoval) {
// If we have no acceptable keys to remove then we are possibly trying to save mission critical data. If this is the case,
// then we should stop retrying as there is not much the user can do to fix this. Instead of getting them stuck in an infinite loop we
// will allow this write to be skipped.
Logger.logAlert('Out of storage. But found no acceptable keys to remove.');
return reportStorageQuota();
}
// Remove the least recently viewed key that is not currently being accessed and retry.
Logger.logInfo(`Out of storage. Evicting least recently accessed key (${keyForRemoval}) and retrying.`);
reportStorageQuota();
return remove(keyForRemoval)
.then(() => onyxMethod(...args));