Skip to content

Commit

Permalink
Merge pull request #171 from Expensify/marcaaron-mergeCollection
Browse files Browse the repository at this point in the history
Add additional documentation for handling collections. Fix behavior of `waitForCollectionCallback`.
  • Loading branch information
tgolen authored Aug 12, 2022
2 parents 1f58aa5 + 7dcd8be commit 6210505
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 1 deletion.
1 change: 1 addition & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ Subscribes a react component's state directly to a store key
| [mapping.withOnyxInstance] | <code>Object</code> | whose setState() method will be called with any changed data This is used by React components to connect to Onyx |
| [mapping.callback] | <code>function</code> | a method that will be called with changed data This is used by any non-React code to connect to Onyx |
| [mapping.initWithStoredValues] | <code>Boolean</code> | If set to false, then no data will be prefilled into the component |
| [mapping.waitForCollectionCallback] | <code>Boolean</code> | If set to true, it will return the entire collection to the callback as a single object |

**Example**
```js
Expand Down
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,80 @@ export default withOnyx({

It is preferable to use the HOC over `Onyx.connect()` in React code as `withOnyx()` will delay the rendering of the wrapped component until all keys have been accessed and made available.

## Collections

Collections allow keys with similar value types to be subscribed together by subscribing to the collection key. To define one, it must be included in the `ONYXKEYS.COLLECTION` object and it must be suffixed with an underscore. Member keys should use a unique identifier or index after the collection key prefix (e.g. `report_42`).

```javascript
const ONYXKEYS = {
COLLECTION: {
REPORT: 'report_',
},
};
```

### Setting Collection Values

To save a new collection key we can either do:

```js
Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${report1.reportID}`, report1);
```

or we can set many at once with `mergeCollection()` (see below for guidance on best practices):

```js
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, {
[`${ONYXKEYS.COLLECTION.REPORT}${report1.reportID}`]: report1,
[`${ONYXKEYS.COLLECTION.REPORT}${report2.reportID}`]: report2,
[`${ONYXKEYS.COLLECTION.REPORT}${report3.reportID}`]: report3,
});
```

### Subscribing to Collections

There are several ways to subscribe to these keys:

```javascript
withOnyx({
allReports: {key: ONYXKEYS.COLLECTION.REPORT},
})(MyComponent);
```

This will add a prop to the component called `allReports` which is an object of collection member key/values. Changes to the individual member keys will modify the entire object and new props will be passed with each individual key update. The prop doesn't update on the initial rendering of the component until the entire collection has been read out of Onyx.

```js
Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT}, callback: (memberValue, memberKey) => {...}});
```

This will fire the callback once per member key depending on how many collection member keys are currently stored. Changes to those keys after the initial callbacks fire will occur when each individual key is updated.

```js
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (allReports) => {...}},
});
```

This final option forces `Onyx.connect()` to behave more like `withOnyx()` and only update the callback once with the entire collection initially and later with an updated version of the collection when individual keys update.

### Performance Considerations When Using Collections

Be cautious when using collections as things can get out of hand if you have a subscriber hooked up to a collection key that has large numbers of individual keys. If this is the case, it is critical to use `mergeCollection()` over `merge()`.

Remember, `mergeCollection()` will notify a subscriber only *once* with the total collected values whereas each call to `merge()` would re-render a connected component *each time it is called*. Consider this example where `reports` is an array of reports that we want to index and save.

```js
// Bad
_.each(reports, report => Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`, report)); // -> A component using withOnyx() will have it's state updated with each iteration

// Good
const values = {};
_.each(reports, report => values[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`] = report);
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, values); // -> A component using withOnyx() will only have it's state updated once
```

## Clean up

To clear all data from `Onyx` we can use `Onyx.clear()`.
Expand Down
17 changes: 16 additions & 1 deletion lib/Onyx.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,15 @@ function keysChanged(collectionKey, collection) {
return;
}

/**
* e.g. Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT, callback: ...});
*/
const isSubscribedToCollectionKey = isKeyMatch(subscriber.key, collectionKey)
&& isCollectionKey(subscriber.key);

/**
* e.g. Onyx.connect({key: `${ONYXKEYS.COLLECTION.REPORT}{reportID}`, callback: ...});
*/
const isSubscribedToCollectionMemberKey = subscriber.key.startsWith(collectionKey);

if (isSubscribedToCollectionKey) {
Expand Down Expand Up @@ -328,7 +335,15 @@ function keyChanged(key, data) {
}

if (_.isFunction(subscriber.callback)) {
if (subscriber.waitForCollectionCallback) {
const cachedCollection = getCachedCollection(subscriber.key);
cachedCollection[key] = data;
subscriber.callback(cachedCollection);
return;
}

subscriber.callback(data, key);
return;
}

if (!subscriber.withOnyxInstance) {
Expand Down Expand Up @@ -397,7 +412,7 @@ function sendDataToConnection(config, val, key) {
* 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 trigger the callback once and return all data as a single object
* @param {Boolean} [mapping.waitForCollectionCallback] If set to true, it will return the entire collection to the callback as a single object
* @returns {Number} an ID to use when calling disconnect
*/
function connect(mapping) {
Expand Down

0 comments on commit 6210505

Please sign in to comment.