This guide shows you how to set up a basic React web application that connects to your Atlas App Services backend and authenticates an anonymous user.
We put together a finished version of this quick start on CodeSandbox. All you have to do is paste in your Realm App ID to connect to your app.
Requisitos previos
This guide assumes that you have already created an Atlas App Services backend and enabled anonymous authentication.
To create and run this application you will need npm installed on your machine.
La documentación de create-react-app recomienda que instales npx para ejecutar
create-react-appen lugar de utilizar una versión que esté instalada en su máquina.
Procedimiento
Set up a New React App
Generate a new application template using create-react-app:
npx create-react-app realm-web-react-quickstart
npx create-react-app realm-web-react-quickstart --template=typescript
Ve a la nueva aplicación e instala el paquete realm-web:
cd realm-web-react-quickstart npm install --save realm-web
Import Dependencies & Connect to Your Realm App
The Realm Web SDK contains everything you need to connect to a MongoDB Realm application from a browser application. In /src/App.js, add the following code to import the Web SDK.
import * as Realm from "realm-web";
Now uses the imported package to instantiate a new Realm.App. The app object represents your Realm app. You'll use it to authenticate and manage the users that interact with your app.
// Add your App ID const app = new Realm.App({ id: APP_ID });
Crear componentes de React
In /src/App.js, add the following components that display details about a given user and allow users to log in.
// Create a component that displays the given user's details function UserDetail({ user }) { return ( <div> <h1>Logged in with anonymous id: {user.id}</h1> </div> ); } // Create a component that lets an anonymous user log in function Login({ setUser }) { const loginAnonymous = async () => { const user = await app.logIn(Realm.Credentials.anonymous()); setUser(user); }; return <button onClick={loginAnonymous}>Log In</button>; }
// Create a component that displays the given user's details const UserDetail = ({ user }: { user: Realm.User }) => { return ( <div> <h1>Logged in with anonymous id: {user.id}</h1> </div> ); }; // Create a component that lets an anonymous user log in type LoginProps = { setUser: (user: Realm.User) => void; }; const Login = ({ setUser }: LoginProps) => { const loginAnonymous = async () => { const user: Realm.User = await app.logIn(Realm.Credentials.anonymous()); setUser(user); }; return <button onClick={loginAnonymous}>Log In</button>; };
Create and Export the App Component
En /src/App.js, sobreescribe el componente App existente con el siguiente componente que almacena el usuario actual en el estado local y renderiza condicionalmente detalles sobre el usuario actual o una pantalla de inicio de sesión si actualmente no hay ningún usuario autenticado.
const App = () => { // Keep the logged in Realm user in local state. This lets the app re-render // whenever the current user changes (e.g. logs in or logs out). const [user, setUser] = React.useState(app.currentUser); // If a user is logged in, show their details. // Otherwise, show the login screen. return ( <div className="App"> <div className="App-header"> {user ? <UserDetail user={user} /> : <Login setUser={setUser} />} </div> </div> ); }; export default App;
const App = () => { // Keep the logged in Realm user in local state. This lets the app re-render // whenever the current user changes (e.g. logs in or logs out). const [user, setUser] = React.useState<Realm.User | null>(app.currentUser); // If a user is logged in, show their details. Otherwise, show the login screen. return ( <div className="App"> <div className="App-header"> {user ? <UserDetail user={user} /> : <Login setUser={setUser} />} </div> </div> ); }; export default App;
Ejecutar la aplicación
You're now ready to connect to your Realm app and log in! Make sure you've saved your changes to /src/App.js and then run the following command from the project root:
yarn start
This starts a local web server that serves your application. If successful, you should see the following output in your shell:
Compiled successfully! You can now view realm-quickstart-web in the browser. Local: http://localhost:3000
Abra http://localhost:3000 en su navegador y compruebe que puede iniciar sesión correctamente como usuario anónimo.
Resumen
Si has completado con éxito esta guía, has creado una aplicación React que puede conectarse a un backend de App Services y autenticar a un usuario anónimo.