Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions API-INTERNAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,7 @@ If the requested key is a collection, it will return an object with all the coll
<dd><p>When a key change happens, search for any callbacks matching the key or collection key and trigger those callbacks</p>
</dd>
<dt><a href="#sendDataToConnection">sendDataToConnection()</a></dt>
<dd><p>Sends the data obtained from the keys to the connection. It either:
- sets state on the withOnyxInstances
- triggers the callback function</p>
<dd><p>Sends the data obtained from the keys to the connection.</p>
</dd>
<dt><a href="#addKeyToRecentlyAccessedIfNeeded">addKeyToRecentlyAccessedIfNeeded()</a></dt>
<dd><p>We check to see if this key is flagged as safe for eviction and add it to the recentlyAccessedKeys list so that when we
Expand Down Expand Up @@ -368,9 +366,7 @@ keyChanged(key, value, subscriber => subscriber.initWithStoredValues === false)
<a name="sendDataToConnection"></a>

## sendDataToConnection()
Sends the data obtained from the keys to the connection. It either:
- sets state on the withOnyxInstances
- triggers the callback function
Sends the data obtained from the keys to the connection.

**Kind**: global function
<a name="addKeyToRecentlyAccessedIfNeeded"></a>
Expand Down
10 changes: 2 additions & 8 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ This method will be deprecated soon. Please use `Onyx.connectWithoutView()` inst
| connectOptions.key | The Onyx key to subscribe to. |
| connectOptions.callback | A function that will be called when the Onyx data we are subscribed changes. |
| connectOptions.waitForCollectionCallback | If set to `true`, it will return the entire collection to the callback as a single object. |
| connectOptions.withOnyxInstance | The `withOnyx` class instance to be internally passed. **Only used inside `withOnyx()` HOC.** |
| connectOptions.statePropertyName | The name of the component's prop that is connected to the Onyx key. **Only used inside `withOnyx()` HOC.** |
| connectOptions.displayName | The component's display name. **Only used inside `withOnyx()` HOC.** |
| connectOptions.selector | This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook or `withOnyx()` HOC.** Using this setting on `useOnyx()` or `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). |
| connectOptions.selector | This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook.** Using this setting on `useOnyx()` 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). |

**Example**
```ts
Expand All @@ -107,10 +104,7 @@ Connects to an Onyx key given the options passed and listens to its changes.
| connectOptions.key | The Onyx key to subscribe to. |
| connectOptions.callback | A function that will be called when the Onyx data we are subscribed changes. |
| connectOptions.waitForCollectionCallback | If set to `true`, it will return the entire collection to the callback as a single object. |
| connectOptions.withOnyxInstance | The `withOnyx` class instance to be internally passed. **Only used inside `withOnyx()` HOC.** |
| connectOptions.statePropertyName | The name of the component's prop that is connected to the Onyx key. **Only used inside `withOnyx()` HOC.** |
| connectOptions.displayName | The component's display name. **Only used inside `withOnyx()` HOC.** |
| connectOptions.selector | This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook or `withOnyx()` HOC.** Using this setting on `useOnyx()` or `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). |
| connectOptions.selector | This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook.** Using this setting on `useOnyx()` 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). |

**Example**
```ts
Expand Down
64 changes: 2 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Awesome persistent storage solution wrapped in a Pub/Sub library.
- Onyx allows other code to subscribe to changes in data, and then publishes change events whenever data is changed
- Anything needing to read Onyx data needs to:
1. Know what key the data is stored in (for web, you can find this by looking in the JS console > Application > local storage)
2. Subscribe to changes of the data for a particular key or set of keys. React function components use the `useOnyx()` hook (recommended), both class and function components can use `withOnyx()` HOC (deprecated, not-recommended) and non-React libs use `Onyx.connect()`.
2. Subscribe to changes of the data for a particular key or set of keys. React function components use the `useOnyx()` hook and non-React libs use `Onyx.connect()`.
3. Get initialized with the current value of that key from persistent storage (Onyx does this by calling `setState()` or triggering the `callback` with the values currently on disk as part of the connection process)
- Subscribing to Onyx keys is done using a constant defined in `ONYXKEYS`. Each Onyx key represents either a collection of items or a specific entry in storage. For example, since all reports are stored as individual keys like `report_1234`, if code needs to know about all the reports (e.g. display a list of them in the nav menu), then it would subscribe to the key `ONYXKEYS.COLLECTION.REPORT`.

Expand Down Expand Up @@ -136,7 +136,7 @@ To teardown the subscription call `Onyx.disconnect()` with the `connectionID` re
Onyx.disconnect(connectionID);
```

We can also access values inside React function components via the `useOnyx()` [hook](https://react.dev/reference/react/hooks) (recommended) or class and function components via the `withOnyx()` [higher order component](https://reactjs.org/docs/higher-order-components.html) (deprecated, not-recommended). When the data changes the component will re-render.
We can also access values inside React function components via the `useOnyx()` [hook](https://react.dev/reference/react/hooks). When the data changes the component will re-render.

```javascript
import React from 'react';
Expand Down Expand Up @@ -168,48 +168,6 @@ if (reportsResult.status === 'loading' || sessionResult.status === 'loading') {
// rest of the component's code.
```

> [!warning]
> ## Deprecated Note
> Please note that the `withOnyx()` Higher Order Component (HOC) is now considered deprecated. Use `useOnyx()` hook instead.

```javascript
import React from 'react';
import {withOnyx} from 'react-native-onyx';

const App = ({session}) => (
<View>
{session.token ? <Text>Logged in</Text> : <Text>Logged out</Text> }
</View>
);

export default withOnyx({
session: {
key: ONYXKEYS.SESSION,
},
})(App);
```

Differently from `useOnyx()`, `withOnyx()` will delay the rendering of the wrapped component until all keys/entities have been fetched and passed to the component, this can be convenient for simple cases. This however, can really delay your application if many entities are connected to the same component.

Additionally, if your component has many keys/entities when your component will mount but will receive many updates as data is fetched from DB and passed down to it, as every key that gets fetched will trigger a `setState` on the `withOnyx` HOC. This might cause re-renders on the initial mounting, preventing the component from mounting/rendering in reasonable time, making your app feel slow and even delaying animations.

You can workaround this by passing an additional object with the `shouldDelayUpdates` property set to true. Onyx will then put all the updates in a queue until you decide when then should be applied, the component will receive a function `markReadyForHydration`. A good place to call this function is on the `onLayout` method, which gets triggered after your component has been rendered.

```javascript
const App = ({session, markReadyForHydration}) => (
<View onLayout={() => markReadyForHydration()}>
{session.token ? <Text>Logged in</Text> : <Text>Logged out</Text> }
</View>
);

// Second argument to funciton is `shouldDelayUpdates`
export default withOnyx({
session: {
key: ONYXKEYS.SESSION
},
}, true)(App);
```

### Dependent Onyx Keys and useOnyx()
Some components need to subscribe to multiple Onyx keys at once and sometimes, one key might rely on the data from another key. This is similar to a JOIN in SQL.

Expand Down Expand Up @@ -246,24 +204,6 @@ export default App;

* It is VERY important to NOT use empty string default values like `report.policyID || ''`. This results in the key returned to `useOnyx` as `policies_`, which subscribes to the ENTIRE POLICY COLLECTION and is most assuredly not what you were intending. You can use a default of `0` (as long as you are reasonably sure that there is never a policyID=0). This allows Onyx to return `undefined` as the value of the policy key, which is handled by `useOnyx` appropriately.

**Detailed explanation of how this is handled and rendered with `withOnyx` HOC:**
1. The component mounts with a `reportID={1234}` prop
2. `withOnyx` evaluates the mapping
3. `withOnyx` connects to the key `reports_1234` because of the prop passed to the component
3. `withOnyx` connects to the key `policies_undefined` because `report` doesn't exist in the props yet, so the `policyID` defaults to `undefined`. * (see note below)
4. Onyx reads the data and updates the state of `withOnyx` with:
- `report={{reportID: 1234, policyID: 1, ... the rest of the object ...}}`
- `policy={undefined}` (since there is no policy with ID `undefined`)
5. There is still an `undefined` key in the mapping, so Onyx reads the data again
6. This time `withOnyx` connects to the key `policies_1` because the `report` object exists in the component's state and it has a `policyID: 1`
7. Onyx reads the data and updates the state of withOnyx with:
- `policy={{policyID: 1, ... the rest of the object ...}`
8. Now all mappings have values that are defined (not undefined) and the component is rendered with all necessary data

* It is VERY important to NOT use empty string default values like `report.policyID || ''`. This results in the key returned to `withOnyx` as `policies_` which subscribes to the ENTIRE POLICY COLLECTION and is most assuredly not what you were intending. You can use a default of `0` (as long as you are reasonably sure that there is never a policyID=0). This allows Onyx to return `undefined` as the value of the policy key, which is handled by `withOnyx` appropriately.

DO NOT use more than one `withOnyx` component at a time. It adds overhead and prevents some optimizations like batched rendering from working to its full potential.

It's also beneficial to use a [selector](https://github.com/Expensify/react-native-onyx/blob/main/API.md#connectmapping--number) with the mapping in case you need to grab a single item in a collection (like a single report action).

### useOnyx()'s `canBeMissing` option
Expand Down
31 changes: 8 additions & 23 deletions lib/Onyx.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as Logger from './Logger';
import cache, {TASK} from './OnyxCache';
import * as PerformanceUtils from './PerformanceUtils';
import Storage from './storage';
import utils from './utils';
import DevTools from './DevTools';
Expand All @@ -11,7 +10,6 @@ import type {
ConnectOptions,
InitOptions,
KeyValueMapping,
Mapping,
OnyxInputKeyValueMapping,
OnyxCollection,
MixedOperationsQueue,
Expand Down Expand Up @@ -41,7 +39,6 @@ function init({
evictableKeys = [],
maxCachedKeysCount = 1000,
shouldSyncMultipleInstances = !!global.localStorage,
debugSetState = false,
enablePerformanceMetrics = false,
skippableCollectionMemberIDs = [],
}: InitOptions): void {
Expand All @@ -56,16 +53,11 @@ function init({

if (shouldSyncMultipleInstances) {
Storage.keepInstancesSync?.((key, value) => {
const prevValue = cache.get(key, false) as OnyxValue<typeof key>;
cache.set(key, value);
OnyxUtils.keyChanged(key, value as OnyxValue<typeof key>, prevValue);
OnyxUtils.keyChanged(key, value as OnyxValue<typeof key>);
});
}

if (debugSetState) {
PerformanceUtils.setShouldDebugSetState(true);
}

if (maxCachedKeysCount > 0) {
cache.setRecentKeysLimit(maxCachedKeysCount);
}
Expand Down Expand Up @@ -94,11 +86,8 @@ function init({
* @param connectOptions.key The Onyx key to subscribe to.
* @param connectOptions.callback A function that will be called when the Onyx data we are subscribed changes.
* @param connectOptions.waitForCollectionCallback If set to `true`, it will return the entire collection to the callback as a single object.
* @param connectOptions.withOnyxInstance The `withOnyx` class instance to be internally passed. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.statePropertyName The name of the component's prop that is connected to the Onyx key. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.displayName The component's display name. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.selector This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook or `withOnyx()` HOC.**
* Using this setting on `useOnyx()` or `withOnyx()` can have very positive performance benefits because the component will only re-render
* @param connectOptions.selector This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook.**
* Using this setting on `useOnyx()` 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).
* @returns The connection object to use when calling `Onyx.disconnect()`.
Expand All @@ -122,11 +111,8 @@ function connect<TKey extends OnyxKey>(connectOptions: ConnectOptions<TKey>): Co
* @param connectOptions.key The Onyx key to subscribe to.
* @param connectOptions.callback A function that will be called when the Onyx data we are subscribed changes.
* @param connectOptions.waitForCollectionCallback If set to `true`, it will return the entire collection to the callback as a single object.
* @param connectOptions.withOnyxInstance The `withOnyx` class instance to be internally passed. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.statePropertyName The name of the component's prop that is connected to the Onyx key. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.displayName The component's display name. **Only used inside `withOnyx()` HOC.**
* @param connectOptions.selector This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook or `withOnyx()` HOC.**
* Using this setting on `useOnyx()` or `withOnyx()` can have very positive performance benefits because the component will only re-render
* @param connectOptions.selector This will be used to subscribe to a subset of an Onyx key's data. **Only used inside `useOnyx()` hook.**
* Using this setting on `useOnyx()` 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).
* @returns The connection object to use when calling `Onyx.disconnect()`.
Expand Down Expand Up @@ -260,7 +246,6 @@ function multiSet(data: OnyxMultiSetInput): Promise<void> {
const keyValuePairsToSet = OnyxUtils.prepareKeyValuePairsForStorage(newData, true);

const updatePromises = keyValuePairsToSet.map(([key, value]) => {
const prevValue = cache.get(key, false);
// When we use multiSet to set a key we want to clear the current delta changes from Onyx.merge that were queued
// before the value was set. If Onyx.merge is currently reading the old value from storage, it will then not apply the changes.
if (OnyxUtils.hasPendingMergeForKey(key)) {
Expand All @@ -269,7 +254,7 @@ function multiSet(data: OnyxMultiSetInput): Promise<void> {

// Update cache and optimistically inform subscribers on the next tick
cache.set(key, value);
return OnyxUtils.scheduleSubscriberUpdate(key, value, prevValue);
return OnyxUtils.scheduleSubscriberUpdate(key, value);
});

return Storage.multiSet(keyValuePairsToSet)
Expand Down Expand Up @@ -476,7 +461,7 @@ function clear(keysToPreserve: OnyxKey[] = []): Promise<void> {

// Notify the subscribers for each key/value group so they can receive the new values
Object.entries(keyValuesToResetIndividually).forEach(([key, value]) => {
updatePromises.push(OnyxUtils.scheduleSubscriberUpdate(key, value, cache.get(key, false)));
updatePromises.push(OnyxUtils.scheduleSubscriberUpdate(key, value));
});
Object.entries(keyValuesToResetAsCollection).forEach(([key, value]) => {
updatePromises.push(OnyxUtils.scheduleNotifyCollectionSubscribers(key, value));
Expand Down Expand Up @@ -764,4 +749,4 @@ function applyDecorators() {
}

export default Onyx;
export type {OnyxUpdate, Mapping, ConnectOptions, SetOptions};
export type {OnyxUpdate, ConnectOptions, SetOptions};
Loading