Colin Riddell
Colin Riddell

Reputation: 427

Realm + React Native best practice user setup with sync

I am experimenting with integrating my app with Realm.io.. as it seems like a pretty awesome platform to use. I am trying to login + register users correctly through something like:

Realm.Sync.User.register('http://realm-ip:9080', this.state.email, this.state.password, (error, user) => {
  if (!error) {
    var realm = new Realm({
      sync: {
        user: user,
        url: 'realm://realm-ip:9080/~/userRealm',
      },
      schema: [PersonSchema, ConversationSchema]
    });
  }
  else {
    console.log(error);
  }
})

This seems to work pretty well. I have similar code for loggin a user into realm. Though, when looking at the Realm JS (React Native) examples here: https://github.com/realm/realm-js/blob/master/examples/ReactExample/components/realm.js they export the realm object with something like:

 export default new Realm({schema: [Todo, TodoList]});

Now, this seems pretty neat, and makes the use of realm flawlessly in the rest of the app. However, it doesn't make use of the sync object with user details in it, as provided when using Realm.Sync.User.* Also I can't figure out the best practice way to achieve this modular design, but still have users login/register via the fist example I showed with Realm.Sync.User.register()

The example app here https://github.com/realm/realm-js/blob/master/examples/ReactExample doesn't give solid examples of registering users.

My questions are:

If my question doesn't make sense, please let me know and I will try to elaborate... as I realise it might not be easy to understand.

Upvotes: 0

Views: 1844

Answers (1)

Kristian Dupont
Kristian Dupont

Reputation: 919

Well, it kind of depends on your situation and there are a number of approaches that could work. I guess you could do something like this:

// realm-container.js

import Realm from 'realm';

export default {
  realm: null,
  initialize: (email, password) => {
    Realm.Sync.User.register('http://realm-ip:9080', email, password, (error, user) => {
      if (!error) {
        this.realm = new Realm({
          sync: {
            user: user,
            url: 'realm://realm-ip:9080/~/userRealm',
          },
          schema: [PersonSchema, ConversationSchema]
        });
      }
      else {
        console.log(error);
      }
    })
  }
};

Then, if you include that as import realmContainer from './realm-container';

you can then call realmContainer.initialize(email, password) and refer to the realm like this: realmContainer.realm

Upvotes: 3

Related Questions