Using Realm with redux

I wanted to know if its possible to use Realm with redux on react-native?

Hi @Tony_Ngomana,

I don’t see a reason why not.

Have you checked our Realm react-native SDK:

Best regards,
Pavel

Yes i have the problem is i’m building a massive app and react context isn’t the right tool for the app. I opted to use redux. But when using it i stumbled upon an error when i tried to export useRealm. I need to use useRealm in a redux-thunk function but however my app won’t compile because of an error caused by user and partitionValue.
my code below:

import Realm from "realm";
import { getRealmApp } from "../functions/realmConfig";
import { ItemSchema } from "./itemSchema";

const app = getRealmApp();

const user: any = Realm.User;

const useConfig = {
  schema: [ItemSchema], //other schema will be added in the future
  sync: {
    user: user.apiKeys,
    partitionValue: user.name,
  },
};

export const useRealm = Realm.open({
  schema: [ItemSchema],
  sync: {
    user: user.prototype,
    partitionValue: app.currentUser?.id!,
  },
});

Hello Tony,

I would highly recommend against putting realm collections and/or items in a redux store, as Realm objects are self-mutating objects, and therefor wont play well with the principles of redux.

That said, there are some issues with the code snippet you supplied:

Realm.User is not a user instance, it’s the class defining a realm-user.

You seem to never actually authenticate a user for sync.
Please see: https://docs.mongodb.com/realm/react-native/quick-start/#authenticate-a-user

So you’ll first need to determine how your users will authenticate? email/password, facebook etc?

When you have a logged in user instance, this can be used in the sync config (and not Realm.User.prototype. If this is in our docs or examples somewhere, please let me know).

Theoretical example (this uses anonymous login):

const openSyncedRealm = async () => {
  const app = getRealmApp();
  const user = await app.logIn(Realm.Credentials.anonymous());
  const realm = await Realm.open({
    schema: [ItemSchema],
    sync: {
      user,
      partitionValue: user.id,
      error: (e) => {
        console.log(e);
      },
    },
  });

  return realm;
};
1 Like

Thank you, guess i will have to look for alternatives