Realm React 0.5.0

Andrew Meyer
Realm Blog

--

📢 Release Announcement: @realm/react v0.5.0 🚀

We are excited to announce the release of @realm/react version 0.5.0! This update brings several enhancements and fixes that will make using Realm even easier in your React Native project. Let's dive into the details of what's new:

Authentication Hooks

We have introduced two new authentication hooks, useAuth and useEmailPasswordAuth, to simplify the authentication process if you rely on MongoDB Atlas App Services. Now you can easily integrate authentication functionality into your React applications using @realm/react. Both of these hooks provide methods that you can call to perform various authentication operations. They will report a state you can use to update your UI while the operations are occurring. Here is an example of a login component that makes use of both useAuth and useEmailPasswordAuth to perform both registration and login.

export const LoginScreen = () => {
const {result, logInWithEmailPassword} = useAuth();
const {register} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

return (
<View style={styles.content}>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
value={email}
onChangeText={setEmail}
autoComplete="email"
textContentType="emailAddress"
autoCapitalize="none"
autoCorrect={false}
placeholder="Email"
/>
</View>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
value={password}
onChangeText={setPassword}
secureTextEntry
autoComplete="password"
textContentType="password"
placeholder="Password"
/>
</View>

{result.error?.operation === AuthOperationName.LogIn && (
<Text style={[styles.error]}>
There was an error logging in, please try again{' '}
</Text>
)}

{result.error?.operation === AuthOperationName.Register && (
<Text style={[styles.error]}>
There was an error registering, please try again
</Text>
)}

<View style={styles.buttons}>
<Pressable
onPress={() => logInWithEmailPassword({email, password})}
style={[styles.button, result.pending && styles.buttonDisabled]}
disabled={result.pending}>
<Text style={buttonStyles.text}>Login</Text>
</Pressable>

<Pressable
onPress={() => register({email, password})}
style={[
styles.button,
result.pending && styles.buttonDisabled,
styles.registerButton,
]}
disabled={result.pending}>
<Text style={buttonStyles.text}>Register</Text>
</Pressable>
</View>
</View>
);
};

The result object returned from both hooks is shared, so you will be able to determine which method is currently being fired.

Check out the usage example in the documentation to get started.

Improved useQuery Syntax

The useQuery function now accepts a query function as an optional parameter. This allows you to call sorted and filtered methods directly within the query, providing more flexibility in querying and retrieving data. Thank you to @levipro for contributing to this enhancement! Here's an example of how you can utilize the new functionality:

const SomeComponent = () => {
const user = useUser();
const items = useQuery(Item,
(res) => res.filtered(`owner_id == "${user?.id}"`).sorted('createdAt'),
[user]
);
};

Default Context for Direct Imports

We have created a default context for the RealmProvider, useQuery, useRealm, and useObject components. As a result, you can now import these components directly from @realm/react without explicitly calling createRealmContext. This change simplifies the import process and improves the overall developer experience. Take a look at the example below:

// These imports are now available without calling `createRealmContext`
import { RealmProvider, useQuery } from '@realm/react';

// Provide your schema models directly to the realm provider
<RealmProvider schema={[Item]}>
<SomeComponent/>
</RealmProvider>
const SomeComponent = () => {
const items = useQuery(Item);
//...
}

NOTE: If your app is using multiple Realms, please continue using createRealmContext as before.

Improved Typing for useUser

We have enhanced the typing for the useUser hook to ensure that it never returns null. Previously, optional chaining was required when accessing the id property. Now, with the improved typing, you can directly access the id property without any typing errors. Here's an example to illustrate the change:

const user = useUser();
// Before
console.log(user?.id); // Optional chaining required
// Now
console.log(user.id); // No typing error

We hope these enhancements and fixes in @realm/react v0.5.0 enhance your development experience and make working with Realm in your React applications even smoother. Feel free to update your package to leverage these new features.

You can also use our react native template or expo template to get started and see these enhancements in action.

If you have any questions or need assistance, please don’t hesitate to reach out to us on GitHub or Community Forum. Happy coding!

--

--

Andrew Meyer
Realm Blog
Writer for

Senior Software Engineer @MongoDB working on Realm JS