1
votes

I am using React Native to build an app that relies on MongoDB Stitch for authentication. More often than not, the app crashes because the client object has not yet loaded when I use it in the following line of code. The error I get is the infamous TypeError: undefined is not an object followed by evaluating 'client.auth.user'.

import React from 'react';
import { View, Text } from 'react-native';
import { Stitch } from 'mongodb-stitch-react-native-sdk';

const APP_ID = '<my app ID>';

const client = Stitch.hasAppClient(APP_ID)
    ? Stitch.getAppClient(APP_ID)
    : Stitch.initializeDefaultAppClient(APP_ID);

const { user } = client.auth;

const Home = () => {
    return (
        <View style={styles.home}>
            <Text>HOME</Text>
            <Text>Hi {user.profile.data.email}</Text>
        </View>
    );
};

export default Home;

const styles = {
    home: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center'
    }
};

The example provided with the MongoDB Stitch NPM package uses componentDidMount (see here), but I am trying to make this work using Hooks. I have tried useEffect, a bunch of if statements, async/await, placing the object in state with useState; No luck.

1
Can I see the mongoDB example ?Bora Sumer
Thanks for your reply! Sure, here's the sample code provided with the package (using componentDidMount): npmjs.com/package/…thePicker

1 Answers

0
votes

So yeah, you can use useEffect hook to instantiate the client and get the user info.

  useEffect(() => {
    _loadClient();
   }, []);

const [client,setClient] = useState({});
const [user,setUser] = useState({});

_loadClient() {
Stitch.initializeDefaultAppClient('<your-client-app-id>').then(client => {
 setClient(client);

  if(client.auth.isLoggedIn) {
    setUser( client.auth.user)
  }
});

}

That should do it.