React Native
...
Users
Registro de Usuarios en React Native con Parse SDK
11 min
registro de usuario para react native introducción en el núcleo de muchas aplicaciones, las cuentas de usuario tienen una noción que permite a los usuarios acceder de forma segura a su información parse proporciona una clase de usuario especializada llamada parse user que maneja automáticamente gran parte de la funcionalidad requerida para la gestión de cuentas de usuario en esta guía, aprenderás cómo parse user parse user funciona creando una función de registro de usuario para tu aplicación react native utilizando el sdk de parse js requisitos previos para completar este tutorial, necesitarás una aplicación react native creada y conectada a back4app objetivo construir una función de registro de usuario utilizando parse para una aplicación react native 1 entendiendo el método signup parse user management utiliza el parse user parse user tipo de objeto, que extiende el parseobject parseobject por defecto mientras contiene métodos auxiliares únicos, como current current y getusername getusername , que te ayudarán a recuperar datos de usuario a lo largo de tu aplicación puedes leer más sobre el parse user parse user objeto aquí en la documentación oficial https //parseplatform org/parse sdk js/api/2 18 0/parse user html en esta guía, aprenderás cómo usar el signup signup método que crea un nuevo parse user parse user válido y único tanto localmente como en el servidor, tomando como argumentos valores válidos de username username y password password 2 crear el componente de registro de usuario ahora construyamos el componente funcional, que llamará al signup signup método en nuestra app primero, crea un nuevo archivo en tu directorio raíz llamado userregistration js userregistration js ( userregistration tsx userregistration tsx si estás usando typescript) y también agrega los elementos de entrada necesarios ( nombre de usuario nombre de usuario y contraseña contraseña ), utilizando hooks de estado a través de usestate usestate para gestionar sus datos userregistration js 1 import react, { fc, reactelement, usestate } from "react"; 2 import { button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration = () => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 return ( 10 <> 11 \<textinput 12 style={styles input} 13 value={username} 14 placeholder={"username"} 15 onchangetext={(text) => setusername(text)} 16 autocapitalize={"none"} 17 /> 18 \<textinput 19 style={styles input} 20 value={password} 21 placeholder={"password"} 22 securetextentry 23 onchangetext={(text) => setpassword(text)} 24 /> 25 \<button title={"sign up"} onpress={() => {}} /> 26 \</> 27 ); 28 }; 29	 30 const styles = stylesheet create({ 31 input { 32 height 40, 33 marginbottom 10, 34 backgroundcolor '#fff', 35 }, 36 }); userregistration tsx 1 import react, { fc, reactelement, usestate } from "react"; 2 import { button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration fc<{}> = ({}) reactelement => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 return ( 10 <> 11 \<textinput 12 style={styles input} 13 value={username} 14 placeholder={"username"} 15 onchangetext={(text) => setusername(text)} 16 autocapitalize={"none"} 17 /> 18 \<textinput 19 style={styles input} 20 value={password} 21 placeholder={"password"} 22 securetextentry 23 onchangetext={(text) => setpassword(text)} 24 /> 25 \<button title={"sign up"} onpress={() => {}} /> 26 \</> 27 ); 28 }; 29	 30 const styles = stylesheet create({ 31 input { 32 height 40, 33 marginbottom 10, 34 backgroundcolor '#fff', 35 }, 36 }); 3 crear una función de registro ahora puedes crear la función de registro que llamará al signup signup método javascript 1 const douserregistration = async function () { 2 // note that these values come from state variables that we've declared before 3 const usernamevalue = username; 4 const passwordvalue = password; 5 // since the signup method returns a promise, we need to call it using await 6 return await parse user signup(usernamevalue, passwordvalue) 7 then((createduser) => { 8 // parse user signup returns the already created parseuser object if successful 9 alert alert( 10 'success!', 11 `user ${createduser getusername()} was successfully created!`, 12 ); 13 return true; 14 }) 15 catch((error) => { 16 // signup can fail if any parameter is blank or failed an uniqueness check on the server 17 alert alert('error!', error message); 18 return false; 19 }); 20 };1 const douserregistration = async function () promise\<boolean> { 2 // note that these values come from state variables that we've declared before 3 const usernamevalue string = username; 4 const passwordvalue string = password; 5 // since the signup method returns a promise, we need to call it using await 6 return await parse user signup(usernamevalue, passwordvalue) 7 then((createduser parse user) => { 8 // parse user signup returns the already created parseuser object if successful 9 alert alert( 10 'success!', 11 `user ${createduser getusername()} was successfully created!`, 12 ); 13 return true; 14 }) 15 catch((error object) => { 16 // signup can fail if any parameter is blank or failed an uniqueness check on the server 17 alert alert('error!', error message); 18 return false; 19 }); 20 }; nota crear un nuevo usuario usando signup signup también lo convierte en el usuario actualmente conectado, por lo que no es necesario que su usuario inicie sesión nuevamente para seguir usando su aplicación inserte esta función dentro del userregistration userregistration componente, justo antes de la return return llamada, para ser llamada y probada recuerde actualizar la acción del botón de registro del formulario onpress onpress a () => douserregistration() () => douserregistration() y para importar alert alert de react native react native su componente ahora debería verse así userregistration js 1 import react, { fc, reactelement, usestate } from "react"; 2 import { alert, button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration = () => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 const douserregistration = async function () { 10 // note that these values come from state variables that we've declared before 11 const usernamevalue = username; 12 const passwordvalue = password; 13 // since the signup method returns a promise, we need to call it using await 14 return await parse user signup(usernamevalue, passwordvalue) 15 then((createduser) => { 16 // parse user signup returns the already created parseuser object if successful 17 alert alert( 18 "success!", 19 `user ${createduser get("username")} was successfully created!` 20 ); 21 return true; 22 }) 23 catch((error) => { 24 // signup can fail if any parameter is blank or failed an uniqueness check on the server 25 alert alert("error!", error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 <> 32 \<textinput 33 style={styles input} 34 value={username} 35 placeholder={"username"} 36 onchangetext={(text) => setusername(text)} 37 autocapitalize={"none"} 38 /> 39 \<textinput 40 style={styles input} 41 value={password} 42 placeholder={"password"} 43 securetextentry 44 onchangetext={(text) => setpassword(text)} 45 /> 46 \<button title={"sign up"} onpress={() => douserregistration()} /> 47 \</> 48 ); 49 }; 50	 51 const styles = stylesheet create({ 52 input { 53 height 40, 54 marginbottom 10, 55 backgroundcolor "#fff", 56 }, 57 }); userregistration tsx 1 import react, { fc, reactelement, usestate } from "react"; 2 import { alert, button, stylesheet, textinput } from "react native"; 3 import parse from "parse/react native"; 4	 5 export const userregistration fc<{}> = ({}) reactelement => { 6 const \[username, setusername] = usestate(""); 7 const \[password, setpassword] = usestate(""); 8	 9 const douserregistration = async function () promise\<boolean> { 10 // note that these values come from state variables that we've declared before 11 const usernamevalue string = username; 12 const passwordvalue string = password; 13 // since the signup method returns a promise, we need to call it using await 14 return await parse user signup(usernamevalue, passwordvalue) 15 then((createduser parse user) => { 16 // parse user signup returns the already created parseuser object if successful 17 alert alert( 18 "success!", 19 `user ${createduser get("username")} was successfully created!` 20 ); 21 return true; 22 }) 23 catch((error object) => { 24 // signup can fail if any parameter is blank or failed an uniqueness check on the server 25 alert alert("error!", error message); 26 return false; 27 }); 28 }; 29	 30 return ( 31 <> 32 \<textinput 33 style={styles input} 34 value={username} 35 placeholder={"username"} 36 onchangetext={(text) => setusername(text)} 37 autocapitalize={"none"} 38 /> 39 \<textinput 40 style={styles input} 41 value={password} 42 placeholder={"password"} 43 securetextentry 44 onchangetext={(text) => setpassword(text)} 45 /> 46 \<button title={"sign up"} onpress={() => douserregistration()} /> 47 \</> 48 ); 49 }; 50	 51 const styles = stylesheet create({ 52 input { 53 height 40, 54 marginbottom 10, 55 backgroundcolor "#fff", 56 }, 57 }); 4 probando el componente el paso final es usar nuestro nuevo componente dentro de tu aplicación react native app js app js archivo (o app tsx app tsx si usas typescript) app js 1 import { userregistration } from " /userregistration"; 2 / 3 your functions here 4 / 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles container}> 9 <> 10 \<text style={styles title}>react native on back4app\</text> 11 \<text>user registration tutorial\</text> 12 \<userregistration /> 13 \</> 14 \</safeareaview> 15 \</> 16 ); 17	 18 // remember to add some styles at the end of your file 19 const styles = stylesheet create({ 20 container { 21 flex 1, 22 backgroundcolor "#fff", 23 alignitems "center", 24 justifycontent "center", 25 }, 26 title { 27 fontsize 20, 28 fontweight "bold", 29 }, 30 }); app tsx 1 import { userregistration } from " /userregistration"; 2 / 3 your functions here 4 / 5 return ( 6 <> 7 \<statusbar /> 8 \<safeareaview style={styles container}> 9 <> 10 \<text style={styles title}>react native on back4app\</text> 11 \<text>user registration tutorial\</text> 12 \<userregistration /> 13 \</> 14 \</safeareaview> 15 \</> 16 ); 17	 18 // remember to add some styles at the end of your file 19 const styles = stylesheet create({ 20 container { 21 flex 1, 22 backgroundcolor "#fff", 23 alignitems "center", 24 justifycontent "center", 25 }, 26 title { 27 fontsize 20, 28 fontweight "bold", 29 }, 30 }); tu aplicación ahora debería verse así después de proporcionar las credenciales de usuario deseadas, verás este mensaje después de presionar en registrarse registrarse si todo fue exitoso el manejo de errores se puede probar si intentas registrar un usuario con el mismo nombre de usuario que antes recibirás otro error si intentas registrarte sin contraseña conclusión al final de esta guía, aprendiste cómo registrar nuevos usuarios de parse en react native en la próxima guía, te mostraremos cómo iniciar y cerrar sesión de los usuarios