React Native에서 Parse로 현재 사용자 데이터 가져오기
현재 사용자 가져오기 위한 React Native
소개
사용자 등록 및 로그인을 구현한 후, 다양한 작업 및 요청을 수행하기 위해 현재 로그인한 사용자 데이터를 검색해야 합니다. React Native는 AsyncStorage를 로컬 저장소로 사용하므로, 이 데이터는 앱의 구성 요소 내에서 Parse.currentAsync를 사용하여 검색할 수 있습니다.
전제 조건
이 튜토리얼을 완료하려면 다음이 필요합니다:
목표
React Native 앱을 위한 Parse를 사용하여 현재 사용자 데이터를 가져옵니다.
1 - 현재 사용자 검색
이 방법 Parse.currentAsync는 앱을 Parse와 AsyncStorage를 사용하도록 적절히 구성한 후 코드 어디에서나 사용할 수 있습니다. 그 응답은 현재 사용자의 객체 (Parse.User) 또는 현재 로그인된 사용자가 없으면 null이 됩니다.
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 };이 방법은 애플리케이션 상태나 사용자 데이터에 접근할 수 없는 상황에서 필수적이며, 앱의 모든 구성 요소에서 관련 Parse 요청을 수행할 수 있게 합니다.
2 - React Native 구성 요소에서 현재 사용자 사용하기
이전 가이드에서 Parse.currentAsync는 테스트와 HelloUser 구성 요소 내에서 이미 사용되었습니다. 여기 다시 전체 구성 요소가 있습니다:
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 };이 경우, Parse.currentAsync 메서드는 사용자 이름을 검색하고 컴포넌트 JSX 내에서 렌더링되는 상태 변수를 업데이트합니다.
결론
이 가이드의 끝에서, React Native에서 로컬 저장소에서 현재 Parse 사용자 데이터를 검색하는 방법을 배웠습니다. 다음 가이드에서는 사용자가 비밀번호를 재설정할 수 있도록 하는 방법을 보여드리겠습니다.