---
title: React Parse에서 현재 사용자 데이터 가져오는 방법
slug: docs-kr/react/working-with-users/get-current-user-react
description: React에서 Parse로 앱을 설정하고 현재 사용자를 가져오는 방법을 알아보세요. 개발자를 위한 상세한 코드 예제와 설명이 포함되어 있습니다.
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-19T17:19:37.911Z
---

# 현재 사용자 가져오기 for React

## 소개

사용자 등록 및 로그인을 구현한 후, 다양한 작업 및 요청을 수행하기 위해 현재 로그인한 사용자 데이터를 검색해야 합니다. 이 데이터는 앱 구성 요소 내에서 <font color="#2166ae">`Parse.User.current`</font>를 사용하여 신속하게 검색할 수 있습니다.

## 전제 조건

:::hint{type="info"}
이 튜토리얼을 완료하려면 다음이 필요합니다:

-  React 앱을 생성하고 [Back4App에 연결](https://www.back4app.com/docs/react/quickstart).
- 이전 가이드를 완료하여 [Parse.User 클래스와 Parse.User.logIn 메서드에 대한 이해를 높이세요.](https://www.back4app.com/docs/react/working-with-users/react-user-login)
- 이 가이드에서 제공하는 화면 레이아웃을 테스트/사용하려면 [<font color="#2166ae">`Ant Design`</font> 라이브러리를 설정해야 합니다.](https://ant.design/docs/react/introduce)
:::

## 목표

React 앱을 위한 Parse를 사용하여 현재 사용자 데이터를 가져옵니다.

## 1 - 현재 사용자 검색

메서드 <font color="#2166ae">`Parse.User.current`</font>는 Parse를 사용하도록 앱을 적절히 구성한 후 코드 어디에서나 사용할 수 있습니다. 그 응답은 현재 사용자의 객체 (<font color="#2166ae">`Parse.User`</font>) 또는 현재 로그인한 사용자가 없으면 null이 됩니다.

:::CodeblockTabs
JavaScript

```javascript
1	const getCurrentUser = async function () {
2	  const currentUser = await Parse.User.current();
3	  if (currentUser !== null) {
4	    Alert.alert(
5	      'Success!',
6	      `${currentUser.get('username')} is the current user!`,
7	    );
8	  }
9	  return currentUser;
10	};
```

```typescript
1	const getCurrentUser = async function (): Promise<Parse.User | null> {
2	  const currentUser: Parse.User = await Parse.User.current();
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 구성 요소에서 현재 사용자 사용하기

이전 가이드에서 <font color="#2166ae">`Parse.User.current`</font> 메서드는 사용자 로그인 가이드에서 현재 사용자 이름을 표시하는 테스트에 이미 사용되었습니다. 다음은 <font color="#2166ae">`UserLogin` </font> 구성 요소 코드입니다. <font color="#2166ae">`getCurrentUser`</font> 함수에 대해 자세히 살펴보세요:

:::CodeblockTabs
UserLogin.js

```javascript
1	import React, { useState } from 'react';
2	import Parse from 'parse/dist/parse.min.js';
3	import './App.css';
4	import { Button, Divider, Input } from 'antd';
5	
6	export const UserLogin = () => {
7	  // State variables
8	  const [username, setUsername] = useState('');
9	  const [password, setPassword] = useState('');
10	  const [currentUser, setCurrentUser] = useState(null);
11	
12	  const doUserLogIn = async function () {
13	    // Note that these values come from state variables that we've declared before
14	    const usernameValue = username;
15	    const passwordValue = password;
16	    try {
17	      const loggedInUser = await Parse.User.logIn(usernameValue, passwordValue);
18	      // logIn returns the corresponding ParseUser object
19	      alert(
20	        `Success! User ${loggedInUser.get(
21	          'username'
22	        )} has successfully signed in!`
23	      );
24	      // To verify that this is in fact the current user, `current` can be used
25	      const currentUser = await Parse.User.current();
26	      console.log(loggedInUser === currentUser);
27	      // Clear input fields
28	      setUsername('');
29	      setPassword('');
30	      // Update state variable holding current user
31	      getCurrentUser();
32	      return true;
33	    } catch (error) {
34	      // Error can be caused by wrong parameters or lack of Internet connection
35	      alert(`Error! ${error.message}`);
36	      return false;
37	    }
38	  };
39	
40	  const doUserLogOut = async function () {
41	    try {
42	      await Parse.User.logOut();
43	      // To verify that current user is now empty, currentAsync can be used
44	      const currentUser = await Parse.User.current();
45	      if (currentUser === null) {
46	        alert('Success! No user is logged in anymore!');
47	      }
48	      // Update state variable holding current user
49	      getCurrentUser();
50	      return true;
51	    } catch (error) {
52	      alert(`Error! ${error.message}`);
53	      return false;
54	    }
55	  };
56	
57	  // Function that will return current user and also update current username
58	  const getCurrentUser = async function () {
59	    const currentUser = await Parse.User.current();
60	    // Update state variable holding current user
61	    setCurrentUser(currentUser);
62	    return currentUser;
63	  };
64	
65	  return (
66	    <div>
67	      <div className="header">
68	        <img
69	          className="header_logo"
70	          alt="Back4App Logo"
71	          src={
72	            'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'
73	          }
74	        />
75	        <p className="header_text_bold">{'React on Back4App'}</p>
76	        <p className="header_text">{'User Login'}</p>
77	      </div>
78	      {currentUser === null && (
79	        <div className="container">
80	          <h2 className="heading">{'User Login'}</h2>
81	          <Divider />
82	          <div className="form_wrapper">
83	            <Input
84	              value={username}
85	              onChange={(event) => setUsername(event.target.value)}
86	              placeholder="Username"
87	              size="large"
88	              className="form_input"
89	            />
90	            <Input
91	              value={password}
92	              onChange={(event) => setPassword(event.target.value)}
93	              placeholder="Password"
94	              size="large"
95	              type="password"
96	              className="form_input"
97	            />
98	          </div>
99	          <div className="form_buttons">
100	            <Button
101	              onClick={() => doUserLogIn()}
102	              type="primary"
103	              className="form_button"
104	              color={'#208AEC'}
105	              size="large"
106	            >
107	              Log In
108	            </Button>
109	          </div>
110	        </div>
111	      )}
112	      {currentUser !== null && (
113	        <div className="container">
114	          <h2 className="heading">{'User Screen'}</h2>
115	          <Divider />
116	          <h2 className="heading">{`Hello ${currentUser.get('username')}!`}</h2>
117	          <div className="form_buttons">
118	            <Button
119	              onClick={() => doUserLogOut()}
120	              type="primary"
121	              className="form_button"
122	              color={'#208AEC'}
123	              size="large"
124	            >
125	              Log Out
126	            </Button>
127	          </div>
128	        </div>
129	      )}
130	    </div>
131	  );
132	};
```

HelloUser.tsx

```typescript
1	import React, { useState, FC, ReactElement } from 'react';
2	import './App.css';
3	import { Button, Divider, Input } from 'antd';
4	const Parse = require('parse/dist/parse.min.js');
5	
6	export const UserLogin: FC<{}> = (): ReactElement => {
7	  // State variables
8	  const [username, setUsername] = useState('');
9	  const [password, setPassword] = useState('');
10	  const [currentUser, setCurrentUser] = useState<Parse.Object | null>(null);
11	
12	  const doUserLogIn = async function (): Promise<boolean> {
13	    // Note that these values come from state variables that we've declared before
14	    const usernameValue: string = username;
15	    const passwordValue: string = password;
16	    try {
17	      const loggedInUser: Parse.User = await Parse.User.logIn(usernameValue, passwordValue);
18	      // logIn returns the corresponding ParseUser object
19	      alert(
20	        `Success! User ${loggedInUser.get('username')} has successfully signed in!`,
21	      );
22	      // To verify that this is in fact the current user, `current` can be used
23	      const currentUser: Parse.User = await Parse.User.current();
24	      console.log(loggedInUser === currentUser);
25	      // Clear input fields
26	      setUsername('');
27	      setPassword('');
28	      // Update state variable holding current user
29	      getCurrentUser();
30	      return true;
31	    } catch (error: any) {
32	      // Error can be caused by wrong parameters or lack of Internet connection
33	      alert(`Error! ${error.message}`);
34	      return false;
35	    }
36	  };
37	
38	  const doUserLogOut = async function (): Promise<boolean> {
39	    try {
40	      await Parse.User.logOut();
41	      // To verify that current user is now empty, currentAsync can be used
42	      const currentUser: Parse.User = await Parse.User.current();
43	      if (currentUser === null) {
44	        alert('Success! No user is logged in anymore!');
45	      }
46	      // Update state variable holding current user
47	      getCurrentUser();
48	      return true;
49	    } catch (error: any) {
50	      alert(`Error! ${error.message}`);
51	      return false;
52	    }
53	  };
54	
55	  // Function that will return current user and also update current username
56	  const getCurrentUser = async function (): Promise<Parse.User | null> {
57	    const currentUser: (Parse.User | null) = await Parse.User.current();
58	    // Update state variable holding current user
59	    setCurrentUser(currentUser);
60	    return currentUser;
61	  }
62	
63	  return (
64	    <div>
65	      <div className="header">
66	        <img
67	          className="header_logo"
68	          alt="Back4App Logo"
69	          src={
70	            'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'
71	          }
72	        />
73	        <p className="header_text_bold">{'React on Back4App'}</p>
74	        <p className="header_text">{'User Login'}</p>
75	      </div>
76	      {currentUser === null &&
77	        (<div className="container">
78	          <h2 className="heading">{'User Login'}</h2>
79	          <Divider />
80	          <div className="form_wrapper">
81	            <Input
82	              value={username}
83	              onChange={(event) => setUsername(event.target.value)}
84	              placeholder="Username"
85	              size="large"
86	              className="form_input"
87	            />
88	            <Input
89	              value={password}
90	              onChange={(event) => setPassword(event.target.value)}
91	              placeholder="Password"
92	              size="large"
93	              type="password"
94	              className="form_input"
95	            />
96	          </div>
97	          <div className="form_buttons">
98	            <Button
99	              onClick={() => doUserLogIn()}
100	              type="primary"
101	              className="form_button"
102	              color={'#208AEC'}
103	              size="large"
104	            >
105	              Log In
106	            </Button>
107	          </div>
108	        </div>)
109	      }
110	      {currentUser !== null &&
111	        (<div className="container">
112	          <h2 className="heading">{'User Screen'}</h2>
113	          <Divider />
114	          <h2 className="heading">{`Hello ${currentUser.get('username')}!`}</h2>
115	          <div className="form_buttons">
116	            <Button
117	              onClick={() => doUserLogOut()}
118	              type="primary"
119	              className="form_button"
120	              color={'#208AEC'}
121	              size="large"
122	            >
123	              Log Out
124	            </Button>
125	          </div>
126	        </div>)
127	      }
128	    </div>
129	  );
130	};
```
:::

이 구성 요소에서 <font color="#2166ae">`Parse.User.current`</font> 메서드는 사용자 이름을 검색하고 구성 요소 JSX 내에서 렌더링되는 상태 변수를 업데이트합니다.

이 클래스를 <font color="#2166ae">`App.css`</font> 파일에 추가하여 레이아웃 스타일을 완전히 렌더링합니다:

:::CodeblockTabs
App.css

```css
1	@import '~antd/dist/antd.css';
2	
3	.App {
4	  text-align: center;
5	}
6	
7	html {
8	  box-sizing: border-box;
9	  outline: none;
10	  overflow: auto;
11	}
12	
13	*,
14	*:before,
15	*:after {
16	  margin: 0;
17	  padding: 0;
18	  box-sizing: inherit;
19	}
20	
21	h1,
22	h2,
23	h3,
24	h4,
25	h5,
26	h6 {
27	  margin: 0;
28	  font-weight: bold;
29	}
30	
31	p {
32	  margin: 0;
33	}
34	
35	body {
36	  margin: 0;
37	  background-color: #fff;
38	}
39	
40	.container {
41	  width: 100%;
42	  max-width: 900px;
43	  margin: auto;
44	  padding: 20px 0;
45	  text-align: left;
46	}
47	
48	.header {
49	  align-items: center;
50	  padding: 25px 0;
51	  background-color: #208AEC;
52	}
53	
54	.header_logo {
55	  height: 55px;
56	  margin-bottom: 20px;
57	  object-fit: contain;
58	}
59	
60	.header_text_bold {
61	  margin-bottom: 3px;
62	  color: rgba(255, 255, 255, 0.9);
63	  font-size: 16px;
64	  font-weight: bold;
65	}
66	
67	.header_text {
68	  color: rgba(255, 255, 255, 0.9);
69	  font-size: 15px;
70	}
71	
72	.heading {
73	  font-size: 22px;
74	}
75	
76	.flex {
77	  display: flex;
78	}
79	
80	.flex_between {
81	  display: flex;
82	  justify-content: space-between;
83	}
84	
85	.flex_child {
86	  flex: 0 0 45%;
87	}
88	
89	.heading_button {
90	  margin-left: 12px;
91	}
92	
93	.list_item {
94	  padding-bottom: 15px;
95	  margin-bottom: 15px;
96	  border-bottom: 1px solid rgba(0,0,0,0.06);
97	  text-align: left;
98	}
99	
100	.list_item_title {
101	  color: rgba(0,0,0,0.87);
102	  font-size: 17px;
103	}
104	
105	.list_item_description {
106	  color: rgba(0,0,0,0.5);
107	  font-size: 15px;
108	}
```
:::

## 결론

이 가이드의 끝에서, 당신은 React에서 로컬 스토리지에서 현재 Parse 사용자 데이터를 검색하는 방법을 배웠습니다. 다음 가이드에서는 사용자가 비밀번호를 재설정할 수 있도록 하는 방법을 보여드리겠습니다.
