Realm & React Native - Best practice to implement auto-updates?

ThorbenA picture ThorbenA · Mar 9, 2016 · Viewed 8.2k times · Source

What are the best practices/patterns make realm a reactive datasource in a react native app? Especially for presentational and container components pattern?

Here is an example which I'd like to make reactive: Realm with React Native

The docs on auto-updates/change-events are a bit thin and the official example does not make use of this feature (to my knowledge).

Answer

Ari picture Ari · Mar 10, 2016

You can make your example reactive by subscribing to events and updating the ui when you receive a change event. Right now events are only sent when write transactions are committed, but finer grained change events will be added in the future. For now you could add the following constructor to update the ui on changes:

constructor(props) {
  super(props);
  this.realm = new Realm({schema:[dogSchema]})
  this.realm.addListener('change', () => {
    this.forceUpdate()
  });
}

You need to hold onto a Realm instance to keep the notifications alive, and you can use this Realm instance throughout the rest of the component.

Instead of calling forceUpdate, you could instead set the component's state or props within the event listener to trigger the refresh, like so:

constructor(props) {
  super(props);

  this.realm = new Realm({schema:[dogSchema]})

  this.state = {...}; // Initial state of component.

  this.realm.addListener('change', () => {
    this.setState({...}); // Update state instead of using this.forceUpdate()
  });
}