React Native
...
Users
React Native: Obtener Usuario Actual con Parse SDK
7 min
obtener el usuario actual para react native introducción después de implementar el registro y el inicio de sesión de usuarios en tu aplicación, necesitas recuperar los datos del usuario actualmente conectado para realizar diferentes acciones y solicitudes dado que react native utiliza asyncstorage asyncstorage como almacenamiento local, estos datos se pueden recuperar utilizando parse currentasync parse currentasync dentro del componente de tu aplicación requisitos previos para completar este tutorial, necesitarás una aplicación de react native creada y conectada a back4app completar las guías anteriores para que puedas tener una mejor comprensión de la clase parse user objetivo obtener los datos del usuario actual utilizando parse para una aplicación de react native 1 recuperando el usuario actual el método parse currentasync parse currentasync se puede usar en cualquier parte de tu código, después de configurar correctamente tu aplicación para usar parse y asyncstorage su respuesta será el objeto de tu usuario actual ( parse user parse user ) o null si no hay un usuario conectado actualmente javascript 1 const getcurrentuser = async function () { 2 const currentuser = await parse user currentasync(); 3 if (currentuser !== null) { 4 alert alert( 5 'success!', 6 `${currentuser get('username')} is the current user!`, 7 ); 8 } 9 return currentuser; 10 };1 const getcurrentuser = async function () promise\<parse user> { 2 const currentuser parse user = await parse user currentasync(); 3 if (currentuser !== null) { 4 alert alert( 5 'success!', 6 `${currentuser get('username')} is the current user!`, 7 ); 8 } 9 return currentuser; 10 }; este método es esencial en situaciones donde no tienes acceso al estado de tu aplicación o a los datos de tu usuario, lo que hace posible realizar solicitudes relevantes de parse en cualquier componente de tu aplicación 2 usando el usuario actual en un componente de react native en nuestras guías anteriores, parse currentasync parse currentasync ya se utilizó para pruebas y dentro del hellouser hellouser componente aquí está el componente completo nuevamente hellouser js 1 import react, {fc, reactelement, useeffect, usestate} from 'react'; 2 import {text, view} from 'react native'; 3 import parse from 'parse/react native'; 4 import styles from ' /styles'; 5	 6 export const hellouser = () => { 7 // state variable that will hold username value 8 const \[username, setusername] = usestate(''); 9	 10 // useeffect is called after the component is initially rendered and 11 // after every other render 12 useeffect(() => { 13 // since the async method parse user currentasync is needed to 14 // retrieve the current user data, you need to declare an async 15 // function here and call it afterwards 16 async function getcurrentuser() { 17 // this condition ensures that username is updated only if needed 18 if (username === '') { 19 const currentuser = await parse user currentasync(); 20 if (currentuser !== null) { 21 setusername(currentuser getusername()); 22 } 23 } 24 } 25 getcurrentuser(); 26 }, \[username]); 27	 28 // note the conditional operator here, so the "hello" text is only 29 // rendered if there is an username value 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 {username !== '' && \<text>{`hello ${username}!`}\</text>} 34 \</view> 35 \</view> 36 ); 37 }; hellouser tsx 1 import react, {fc, reactelement, useeffect, usestate} from 'react'; 2 import {text, view} from 'react native'; 3 import parse from 'parse/react native'; 4 import styles from ' /styles'; 5	 6 export const hellouser fc<{}> = ({}) reactelement => { 7 // state variable that will hold username value 8 const \[username, setusername] = usestate(''); 9	 10 // useeffect is called after the component is initially rendered and 11 // after every other render 12 useeffect(() => { 13 // since the async method parse user currentasync is needed to 14 // retrieve the current user data, you need to declare an async 15 // function here and call it afterwards 16 async function getcurrentuser() { 17 // this condition ensures that username is updated only if needed 18 if (username === '') { 19 const currentuser = await parse user currentasync(); 20 if (currentuser !== null) { 21 setusername(currentuser getusername()); 22 } 23 } 24 } 25 getcurrentuser(); 26 }, \[username]); 27	 28 // note the conditional operator here, so the "hello" text is only 29 // rendered if there is an username value 30 return ( 31 \<view style={styles login wrapper}> 32 \<view style={styles form}> 33 {username !== '' && \<text>{`hello ${username}!`}\</text>} 34 \</view> 35 \</view> 36 ); 37 }; en este caso, el parse currentasync parse currentasync método recupera el nombre de usuario y actualiza la variable de estado que se renderiza dentro del jsx del componente conclusión al final de esta guía, aprendiste cómo recuperar los datos del usuario actual de parse desde el almacenamiento local en react native en la próxima guía, te mostraremos cómo permitir que tu usuario restablezca su contraseña