Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Referencia de API

AppProvider (@realm/react)

Type signature
AppProvider(props, context?): null | ReactElement<any, any>

Componentes anidados dentro AppProvider puede acceder a su aplicación de servicios de aplicaciones y utilizar los ganchos AppProvider.

Todas las propiedades de AppConfiguration se puede pasar como propiedad AppProvider a.

Para configurar el cliente de la aplicación, pasa la cadena de ID de la aplicación a la propiedad id de AppProvider. Encapsula cualquier componente que necesite acceder a la aplicación con AppProvider.

import React from 'react';
import {AppProvider} from '@realm/react';
function AppWrapper() {
return (
<View>
<AppProvider id={APP_ID}>
<MyApp />
</AppProvider>
</View>
);
}

Puedes crear varias instancias de un cliente de aplicación para conectarte a múltiples aplicaciones. Todas las instancias de cliente de aplicación que comparten el mismo ID de la aplicación utilizan la misma conexión subyacente.

Importante

Changing an App Config After Initializing the App

Cambiado en la versión realm@12.6.0: baseUrl no está almacenado en caché

Cuando inicias el cliente de la aplicación, la configuración se almacena en caché internamente. El intentar "cerrar" y luego reabrir una aplicación con una configuración modificada dentro del mismo proceso no tiene efecto. El cliente continúa utilizando la configuración almacenada en caché.

Starting with React Native SDK version 12.6.0, the baseUrl in the AppConfiguration is not cached. This means that you can change the baseUrl and the App client will use the updated configuration. In earlier SDK versions, changes to the baseUrl in a cached App configuration have no effect.

Type signature
useAuth(): UseAuth

useAuth has an authentication method for every App Services authentication provider.

Type signature
result: AuthResult

Resultado de la operación del hook de autenticación. Por ejemplo, result.operation le ofrece el nombre de la operación actual.

Enum values

  • state. Puede ser "not-started", "pending", "éxito", "error".

  • operation. Para obtener una lista de todos los nombres de operaciones, consulta la documentación de la API.

  • pending. Puede ser true o false.

  • success. Puede ser true o false.

  • error. Objeto basado en error o indefinido.

Type signature
logIn(credentials: Realm.Credentials): void

Parámetros

  • credentials. A Realm credential supplied by any supported Realm authentication.

Ejemplo

Logs in a user with any authentication mechanism supported by Realm. If called when a user is logged in, the current user switches to the new user. Usually, it's better to use the more specific login methods.

const {logIn, result} = useAuth();
useEffect(() => logIn(Realm.Credentials.anonymous()), []);
if(result.pending) {
return (<LoadingSpinner/>)
}
if(result.error) {
return (<ErrorComponent/>)
}
if(result.success) {
return (<SuccessComponent/>)
}
//...
Type signature
logInWithAnonymous(): void

Ejemplo

Inicia sesión con el proveedor de autenticación anónima.

const {logInWithAnonymous, result} = useAuth();
const performLogin = () => {
logInWithAnonymous();
};
Type signature
logInWithApiKey(key: string): void

Parámetros

  • key. A string that is linked to an App Services user.

Ejemplo

Log in with an API key.

const {logInWithApiKey, result} = useAuth();
const performLogin = () => {
const key = getApiKey(); // user defined function
logInWithApiKey(key);
};
Type signature
logInWithEmailPassword(credentials: {
email: string;
password: string;
}): void

Parámetros

  • credentials. An object with email and password fields.

Ejemplo

Inicia sesión con correo electrónico/contraseña.

const {logInWithEmailPassword, result} = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performLogin = () => {
logInWithEmailPassword({email, password});
};
Type signature
logInWithJWT(token: string): void

Parámetros

  • credentials. A string representation of a user's JWT.

Ejemplo

Iniciar sesión con un JSON Web Token (JWT).

const {logInWithJWT, result} = useAuth();
const performLogin = () => {
const token = authorizeWithCustomerProvider(); // user defined function
logInWithJWT(token);
};
Type signature
logInWithGoogle(credentials: {
idToken: string;
} | {
authCode: string;
}): void;

Parámetros

  • credentials. An object with an idToken or authCode field that should contain the string token you get from Google Identity Services.

Ejemplo

Inicia sesión con Google.

const {logInWithGoogle, result} = useAuth();
const performLogin = () => {
const token = getGoogleToken(); // user defined function
logInWithGoogle({idToken: token});
};
Type signature
logInWithApple(idToken: string): void;

Parámetros

  • idToken. A string you get from the Apple SDK.

Ejemplo

Log in with Apple.

const {logInWithApple, result} = useAuth();
const performLogin = () => {
const token = getAppleToken(); // user defined function
logInWithApple(token);
};
Type signature
logInWithFacebook(accessToken: string): void;

Parámetros

  • accessToken. A string you get from the Facebook SDK.

Ejemplo

Inicia sesión con Facebook.

const {logInWithFacebook, result} = useAuth();
const performLogin = () => {
const token = getFacebookToken(); // user defined function
logInWithFacebook(token);
};
Type signature
logInWithFunction<PayloadType extends Record<string, unknown>>(payload: PayloadType): void;

Parámetros

  • payload. An object that contains user information you want to pass to the App Services function that processes log in requests.

Ejemplo

Log in with a custom function.

const {logInWithFunction, result} = useAuth();
const performLogin = () => {
const customPayload = getAuthParams(); // user defined arguments
logInWithFunction(customPayload);
};
Type signature
logOut(): void;

Ejemplo

Cierra la sesión del usuario actual.

const {logOut, result} = useEmailPasswordAuth();
const performLogout = () => {
logOut();
}
Type signature
result: AuthResult

Resultado de la operación del hook de autenticación. Por ejemplo, result.operation le ofrece el nombre de la operación actual.

Enum values

  • state. Puede ser "not-started", "pending", "éxito", "error".

  • operation. Para obtener una lista de todos los nombres de operaciones, consulta la documentación de la API.

  • pending. Puede ser true o false.

  • success. Puede ser true o false.

  • error. Objeto basado en error o indefinido.

Type signature
logIn(credentials: { email: string; password: string }): void;

Parámetros

  • credentials. An object that contains email and password properties.

Ejemplo

Logs a user in using an email and password. You could also call logIn(Realm.Credentials.emailPassword(email, password)). Returns a Realm.User instance of the logged-in user.

const {logIn, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performLogin = () => {
logIn({email, password});
};
if(result.pending) {
return (<LoadingSpinner/>)
}
if(result.error) {
return (<ErrorComponent/>)
}
if(result.success) {
return (<SuccessComponent/>)
}
//...
Type signature
logOut(): void;

Ejemplo

Cierra la sesión del usuario actual.

const {logOut, result} = useEmailPasswordAuth();
const performLogout = () => {
logOut();
}
Type signature
register(args: { email: string; password: string }): void;

Parámetros

  • args. An object that contains email and password properties.

Ejemplo

Registers a new user. Requires a user email and password.

const {register, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performRegister = () => {
register({email, password});
};
Type signature
confirm(args: { token: string; tokenId: string }): void;

Parámetros

  • args. An object that contains token and tokenId properties.

Ejemplo

Confirma una cuenta de usuario. Requiere token y tokenId.

const {confirm, result} = useEmailPasswordAuth();
const performConfirmation = () => {
confirm({token, tokenId});
};
Type signature
resendConfirmationEmail(args: { email: string }): void;

Parámetros

  • args. An object that contains an email property.

Ejemplo

Reenvía un correo electrónico de confirmación.

const {resendConfirmationEmail, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const performResendConfirmationEmail = () => {
resendConfirmationEmail({email});
};
Type signature
retryCustomConfirmation(args: { email: string }): void;

Parámetros

  • args. An object that contains an email property.

Ejemplo

Vuelve a intentar la confirmación con una función personalizada.

const {retryCustomConfirmation, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const performRetryCustomConfirmation = () => {
retryCustomConfirmation({email});
};
Type signature
sendResetPasswordEmail(args: { email: string }): void;

Parámetros

  • args. An object that contains an email property.

Ejemplo

Envía un correo electrónico de restablecimiento de contraseña.

const {sendResetPasswordEmail, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const performSendResetPasswordEmail = () => {
sendResetPasswordEmail({email});
};
Type signature
resetPassword(args: { token: string; tokenId: string; password: string }): void;

Parámetros

  • args. An object that contains token, tokenId, and password properties.

Ejemplo

Resets a user's password.

const {resetPassword, result} = useEmailPasswordAuth();
const [password, setPassword] = useState('');
const performResetPassword = () => {
resetPassword({token, tokenId, password});
};
Type signature
callResetPasswordFunction<Args extends unknown[] = []>(
args: {
email: string;
password: string;
},
...restArgs: Args
): void;

Parámetros

  • args. An object that contains email and password properties.

  • restArgs. Additional arguments that you need to pass to your custom reset password function.

Ejemplo

Calls your App Services backend password reset function. Can pass arguments to the function as needed.

const {callResetPasswordFunction, result} = useEmailPasswordAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const performResetPassword = () => {
callResetPasswordFunction({email, password}, "extraArg1", "extraArg2");
};
Type signature
useApp<FunctionsFactoryType, CustomDataType>(): Realm.App<FunctionsFactoryType, CustomDataType>

Ejemplo

El useApp() gancho proporciona acceso a una instancia de Realm.App.

import React from 'react';
import {useApp} from '@realm/react';
function MyApp() {
const app = useApp();
// Proceed to app logic...
}

Devuelve

  • Realm.App An instance of the current Realm.App created by AppProvider.

Volver

RealmProvider (@realm/react)