mongodbreact-nativemongodb-stitch

ReactNative MongoDB default app client has not yet been initialized/set


I'm new to ReactNative, and I am trying to connect MongoDB Atlas to my RN app. I'm getting an error saying default app client has not yet been initialized/set even though I'm calling the Stitch.initializeDefaultAppClient(MONGODB_APP_CLIENT) method.

I followed this tutorial: https://levelup.gitconnected.com/react-native-mongodb-stitch-building-a-crud-application-without-a-server-3e4ae0b34d67

In App.js:

import { Stitch, AnonymousCredential } from "mongodb-stitch-react-native-sdk";
...
_loadClient() {
    Stitch.initializeDefaultAppClient(MONGODB_APP_CLIENT).then(client => {
      this.setState({ client });
      this.state.client.auth
        .loginWithCredential(new AnonymousCredential())
        .then(user => {
          console.log(`Successfully logged in as user ${user.id}`);
          this.setState({ currentUserId: user.id });
          this.setState({ currentUserId: client.auth.user.id });
        })
        .catch(err => {
          console.log(`Failed to log in anonymously: ${err}`);
          this.setState({ currentUserId: undefined });
        });
    });
  }
}
...

In Contacts.js:

import { Stitch, RemoteMongoClient } from "mongodb-stitch-react-native-sdk";
..
constructor() {
        super();
        this.state = {
          isLoading: true,
          users: []
        };

        this._loadClient = this._loadClient.bind(this);
    }
    componentDidMount() {
        this._loadClient();
    }

_loadClient() {
        const stitchAppClient = Stitch.defaultAppClient;
        const mongoClient = stitchAppClient.getServiceClient(
          RemoteMongoClient.factory,
          "mongodb-atlas"
        );
        const db = mongoClient.db("dbapp");
        const users = db.collection("users");
        users
          .find({ status: "new" }, { sort: { date: -1 } })
          .asArray()
          .then(docs => {
            this.setState({ users });
          })
          .catch(err => {
            console.warn(err);
          });
    }
...

Above, I'm sharing the code that is necessary for this to work. I have it all in my code, and even though I initialized the app client, I'm still getting an error. Would love all the help I can get here!

Full error message:

Error: default app client has not yet been initialized/set

This error is located at:
    in Contacts (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:910)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewCard.tsx:106)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at screens.native.js:71)
    in Screen (at StackViewCard.tsx:93)
    in Card (at createPointerEventsContainer.tsx:95)
    in Container (at StackViewLayout.tsx:985)
    in RCTView (at View.js:45)
    in View (at screens.native.js:101)
    in ScreenContainer (at StackViewLayout.tsx:394)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewLayout.tsx:384)
    in PanGestureHandler (at StackViewLayout.tsx:377)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.tsx:104)
    in RCTView (at View.js:45)
    in View (at Transitioner.tsx:267)
    in Transitioner (at StackView.tsx:41)
    in StackView (at createNavigator.js:81)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (at SceneView.js:9)
    in SceneView (at createTabNavigator.js:39)
    in RCTView (at View.js:45)
    in View (at ResourceSavingScene.js:37)
    in RCTView (at View.js:45)
    in View (at ResourceSavingScene.js:26)
    in ResourceSavingScene (at createBottomTabNavigator.js:120)
    in RCTView (at View.js:45)
    in View (at screens.native.js:101)
    in ScreenContainer (at createBottomTabNavigator.js:110)
    in RCTView (at View.js:45)
    in View (at createBottomTabNavigator.js:109)
    in TabNavigationView (at createTabNavigator.js:197)
    in NavigationView (at createNavigator.js:81)
    in Navigator (at SceneView.js:9)
    in SceneView (at SwitchView.js:12)
    in SwitchView (at createNavigator.js:81)
    in Navigator (at createAppContainer.js:430)
    in NavigationContainer (at App.js:38)
    in RCTView (at View.js:45)
    in View (at App.js:36)
    in App (at withExpoRoot.js:20)
    in RootErrorBoundary (at withExpoRoot.js:19)
    in ExpoRootComponent (at renderApplication.js:35)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:98)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:115)
    in AppContainer (at renderApplication.js:34)

Function.get [as defaultAppClient]
    106aa394-9652-42d9-8b6b-cda0fd593b63:183243:17
Contacts._loadClient
    106aa394-9652-42d9-8b6b-cda0fd593b63:152692:67
Contacts.proxiedMethod
    106aa394-9652-42d9-8b6b-cda0fd593b63:47391:32
Contacts.componentDidMount
    106aa394-9652-42d9-8b6b-cda0fd593b63:152685:14
Contacts.proxiedComponentDidMount
    106aa394-9652-42d9-8b6b-cda0fd593b63:47404:42
commitLifeCycles
    106aa394-9652-42d9-8b6b-cda0fd593b63:21888:28
commitAllLifeCycles
    106aa394-9652-42d9-8b6b-cda0fd593b63:23239:13
Object.invokeGuardedCallbackImpl
    106aa394-9652-42d9-8b6b-cda0fd593b63:11985:16
invokeGuardedCallback
    106aa394-9652-42d9-8b6b-cda0fd593b63:12076:37
commitRoot
    106aa394-9652-42d9-8b6b-cda0fd593b63:23433:13

As an update, this error is randomly occurring, and randomly not occurring. One minute it loads my data, and next time I save the file (and the app reloads), I get the error again. Reloading a bunch of times ends up fixing it. But then, of course, it'll happen again.


Solution

  • The following changes seem to have worked:

    App.js:

    _loadClient() {
        Stitch.initializeDefaultAppClient(MONGODB_APP_CLIENT)
        .then(client => {
          client.auth
            .loginWithCredential(new AnonymousCredential())
            .then(user => {
              console.log(`Successfully logged in as user ${user.id}`);
              this.setState({
                currentUserId: user.id,
                currentUserId: client.auth.user.id,
                client,
              });
            })
            .catch(err => {
              console.log(`Failed to log in anonymously: ${err}`);
              this.setState({
                currentUserId: undefined,
                client,
              });
            });
        })
        .catch(err => {
          console.error(err)
        });
      }
    

    Contacts.js:

    _loadClient() {
            if (Stitch.hasAppClient(MONGODB_APP_CLIENT)) {
              const app = Stitch.getAppClient(MONGODB_APP_CLIENT);
              this._loadData(app);
            } else {
              Stitch.initializeAppClient(MONGODB_APP_CLIENT)
              .then(app => this._loadData(app))
              .catch(err => console.error(err));
            }
        }
    _loadData(appClient) {
          const mongoClient = appClient.getServiceClient(
              RemoteMongoClient.factory,
              "mongodb-atlas"
            );
            const db = mongoClient.db("sidapp");
            const users = db.collection("users");
            users
              .find({ type: 2 })
              .asArray()
              .then(users => {
                this.setState({ users });
              })
              .catch(err => {
                console.warn(err);
              });
        }