Painfully Close to Getting Realm Sync to Work with Custom Data

Hi all - hoping someone can help me with sync; I am currently building a mobile application with React Native. I’ve gotten to the point where I think I have everything set up as best as possible but am running into one last barrier where sync is not instantly updating my application.

Specifically, I have done the following:

  1. Setup email/password authentication which calls an authentication trigger that creates and saves the new user’s realm id as the field ‘realmId’ in a new document to a collection called athletes (so i have an _id and realmId field in each athlete document. I have no issues logging in, signing up, or logging out athletes.
  2. Enabled custom user data with the User ID field ‘realmId’.
  3. Autogenerated the realm schema for athletes based on the existing data in the collection. The field realmId (which will become my partition key on sync) was pulled in correctly and has the type string, for simplicity the only other field to note is ‘name’ for the athletes name. The athletes collection allows read and write permissions.
  4. I copied the User Realm Object Model from the SDK section into my project under a new file schemas.js. I am exporting the schema as ‘athleteSchema’ with the name: ‘athlete’.
  5. I enabled a partition based sync with partition key ‘realmId’. The read and write permissions are identical
    { “%%partition”: “%%user.id” }.
  6. I updated my AuthProvider.js file (which mostly matched this tutorial https://docs.mongodb.com/realm/tutorial/react-native/) to sync with the current user/athlete.
import React, { useContext, useState, useEffect, useRef } from "react";
import Realm from "realm";
import app from '../../realmApp';
import { athleteSchema } from "../schemas";

const AuthContext = React.createContext(null);

const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(app.currentUser)
    const realmRef = useRef(null);

    useEffect(() => {  

        const OpenRealmBehaviorConfiguration = {
            type: "openImmediately"
        }

        const config = {
            schema: [athleteSchema],
            sync: {
                user: app.currentUser,
                partitionValue: `user=${user.id}`,
                newRealmFileBehavior: OpenRealmBehaviorConfiguration,
                existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
            }
        }

        Realm.open(config).then((userRealm) => {
            realmRef.current = userRealm
            const athletes = userRealm.objects("athlete")

            // I think this is the part where I am stuck 
            athletes.addListener(() => {
                if (athletes.length === 0) {
                    setUser(user)
                }
            })
        })

        return () => {
            const userRealm = realmRef.current
            if (userRealm) {
                userRealm.close()
                realmRef.current = null
            }
        }

    }, [user])

    return (
        <AuthContext.Provider value={{ user }}>
              {children}
        </AuthContext.Provider>
    )

   const useAuth = () => {
       const auth = useContext(AuthContext)
       if (auth == null) {
           throw new Error("useAuth() called outside of a AuthProvider?")
       }
       return auth
   }

    // Excluded sign in, sign out, etc. functions for ease

export { AuthProvider, useAuth }
  1. Using react navigation, I go to the athlete’s profile page. I can fetch the athlete’s name with useAuth.
const { user } = useAuth()
const [name, setName] = useState(user.customData.name)

console.log(name)
  1. Since I know that custom data is working properly, I shifted my focus to sync. Remaining on the athlete’s profile page, I set up the following
     useEffect(() => {
        async function fetchRealm () {
            try {
                const profile = await user.refreshCustomData()
                setName(profile.name)
                console.log(name)
            } catch (error) {
                console.error(error)
            }
        }
        fetchRealm()
    }, [])

At this point, sync is ‘working’, sweet! For example, I changed the athlete’s name directly in Atlas. If i start on my home screen and click a button to go to the athlete’s profile page, the athlete’s name is updated. BUT if I remain on the athlete’s profile page and make an update to Atlas the changes I made to the athlete’s name are not currently being observed by my application. The best I can do is return to the home screen and then go back to the profile page and then can see the current athlete name.

I feel like I am missing something with the listener I set up in the AuthProvider.js but am struggling to figure out what changes need to be made here.

Thanks for the help in advance!