Get current User for React
Introduction
After implementing user registration and login to your, you need to retrieve the currently logged user data to perform different actions and requests. This data can be promptly retrieved by using Parse.User.current
inside your app components.
Prerequisites
To complete this tutorial, you will need:
- A React App created and connected to Back4App.
- Complete the previous guides so you can have a better understanding of the Parse.User class.
- If you want to test/use the screen layout provided by this guide, you should set up the
Ant Design
library.
Goal
Get the current user data fetching using Parse for a React app.
Step 1 - Retrieving Current User
The method Parse.User.current
can be used anywhere on your code, after properly configuring your app to use Parse. Its response will be your current user’s object (Parse.User
) or null if there is no logged-in user currently.
1
2
3
4
5
6
7
8
9
10
const getCurrentUser = async function () {
const currentUser = await Parse.User.current();
if (currentUser !== null) {
Alert.alert(
'Success!',
`${currentUser.get('username')} is the current user!`,
);
}
return currentUser;
};
1
2
3
4
5
6
7
8
9
10
const getCurrentUser = async function (): Promise<Parse.User | null> {
const currentUser: Parse.User = await Parse.User.current();
if (currentUser !== null) {
Alert.alert(
'Success!',
`${currentUser.get('username')} is the current user!`,
);
}
return currentUser;
};
This method is essential in situations where you don’t have access to your application state or your user data, making it possible to perform relevant Parse requests in any component of your app.
Step 2 - Using Current User in a React component
In our previous guides, the Parse.User.current
method was already used for testing showing the current username on the User Login guide. Here is the UserLogin
component code, take a closer look at the getCurrentUser
function:
UserLogin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import React, { useState } from 'react';
import Parse from 'parse/dist/parse.min.js';
import './App.css';
import { Button, Divider, Input } from 'antd';
export const UserLogin = () => {
// State variables
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [currentUser, setCurrentUser] = useState(null);
const doUserLogIn = async function () {
// Note that these values come from state variables that we've declared before
const usernameValue = username;
const passwordValue = password;
try {
const loggedInUser = await Parse.User.logIn(usernameValue, passwordValue);
// logIn returns the corresponding ParseUser object
alert(
`Success! User ${loggedInUser.get(
'username'
)} has successfully signed in!`
);
// To verify that this is in fact the current user, `current` can be used
const currentUser = await Parse.User.current();
console.log(loggedInUser === currentUser);
// Clear input fields
setUsername('');
setPassword('');
// Update state variable holding current user
getCurrentUser();
return true;
} catch (error) {
// Error can be caused by wrong parameters or lack of Internet connection
alert(`Error! ${error.message}`);
return false;
}
};
const doUserLogOut = async function () {
try {
await Parse.User.logOut();
// To verify that current user is now empty, currentAsync can be used
const currentUser = await Parse.User.current();
if (currentUser === null) {
alert('Success! No user is logged in anymore!');
}
// Update state variable holding current user
getCurrentUser();
return true;
} catch (error) {
alert(`Error! ${error.message}`);
return false;
}
};
// Function that will return current user and also update current username
const getCurrentUser = async function () {
const currentUser = await Parse.User.current();
// Update state variable holding current user
setCurrentUser(currentUser);
return currentUser;
};
return (
<div>
<div className="header">
<img
className="header_logo"
alt="Back4App Logo"
src={
'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'
}
/>
<p className="header_text_bold">{'React on Back4App'}</p>
<p className="header_text">{'User Login'}</p>
</div>
{currentUser === null && (
<div className="container">
<h2 className="heading">{'User Login'}</h2>
<Divider />
<div className="form_wrapper">
<Input
value={username}
onChange={(event) => setUsername(event.target.value)}
placeholder="Username"
size="large"
className="form_input"
/>
<Input
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Password"
size="large"
type="password"
className="form_input"
/>
</div>
<div className="form_buttons">
<Button
onClick={() => doUserLogIn()}
type="primary"
className="form_button"
color={'#208AEC'}
size="large"
>
Log In
</Button>
</div>
</div>
)}
{currentUser !== null && (
<div className="container">
<h2 className="heading">{'User Screen'}</h2>
<Divider />
<h2 className="heading">{`Hello ${currentUser.get('username')}!`}</h2>
<div className="form_buttons">
<Button
onClick={() => doUserLogOut()}
type="primary"
className="form_button"
color={'#208AEC'}
size="large"
>
Log Out
</Button>
</div>
</div>
)}
</div>
);
};
HelloUser.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import React, { useState, FC, ReactElement } from 'react';
import './App.css';
import { Button, Divider, Input } from 'antd';
const Parse = require('parse/dist/parse.min.js');
export const UserLogin: FC<{}> = (): ReactElement => {
// State variables
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [currentUser, setCurrentUser] = useState<Parse.Object | null>(null);
const doUserLogIn = async function (): Promise<boolean> {
// Note that these values come from state variables that we've declared before
const usernameValue: string = username;
const passwordValue: string = password;
try {
const loggedInUser: Parse.User = await Parse.User.logIn(usernameValue, passwordValue);
// logIn returns the corresponding ParseUser object
alert(
`Success! User ${loggedInUser.get('username')} has successfully signed in!`,
);
// To verify that this is in fact the current user, `current` can be used
const currentUser: Parse.User = await Parse.User.current();
console.log(loggedInUser === currentUser);
// Clear input fields
setUsername('');
setPassword('');
// Update state variable holding current user
getCurrentUser();
return true;
} catch (error: any) {
// Error can be caused by wrong parameters or lack of Internet connection
alert(`Error! ${error.message}`);
return false;
}
};
const doUserLogOut = async function (): Promise<boolean> {
try {
await Parse.User.logOut();
// To verify that current user is now empty, currentAsync can be used
const currentUser: Parse.User = await Parse.User.current();
if (currentUser === null) {
alert('Success! No user is logged in anymore!');
}
// Update state variable holding current user
getCurrentUser();
return true;
} catch (error: any) {
alert(`Error! ${error.message}`);
return false;
}
};
// Function that will return current user and also update current username
const getCurrentUser = async function (): Promise<Parse.User | null> {
const currentUser: (Parse.User | null) = await Parse.User.current();
// Update state variable holding current user
setCurrentUser(currentUser);
return currentUser;
}
return (
<div>
<div className="header">
<img
className="header_logo"
alt="Back4App Logo"
src={
'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'
}
/>
<p className="header_text_bold">{'React on Back4App'}</p>
<p className="header_text">{'User Login'}</p>
</div>
{currentUser === null &&
(<div className="container">
<h2 className="heading">{'User Login'}</h2>
<Divider />
<div className="form_wrapper">
<Input
value={username}
onChange={(event) => setUsername(event.target.value)}
placeholder="Username"
size="large"
className="form_input"
/>
<Input
value={password}
onChange={(event) => setPassword(event.target.value)}
placeholder="Password"
size="large"
type="password"
className="form_input"
/>
</div>
<div className="form_buttons">
<Button
onClick={() => doUserLogIn()}
type="primary"
className="form_button"
color={'#208AEC'}
size="large"
>
Log In
</Button>
</div>
</div>)
}
{currentUser !== null &&
(<div className="container">
<h2 className="heading">{'User Screen'}</h2>
<Divider />
<h2 className="heading">{`Hello ${currentUser.get('username')}!`}</h2>
<div className="form_buttons">
<Button
onClick={() => doUserLogOut()}
type="primary"
className="form_button"
color={'#208AEC'}
size="large"
>
Log Out
</Button>
</div>
</div>)
}
</div>
);
};
In this component, the Parse.User.current
method retrieves the username and updates the state variable that is rendered inside the component JSX.
Add these classes to your App.css
file to fully render the layout styles:
App.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
@import '~antd/dist/antd.css';
.App {
text-align: center;
}
html {
box-sizing: border-box;
outline: none;
overflow: auto;
}
*,
*:before,
*:after {
margin: 0;
padding: 0;
box-sizing: inherit;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
font-weight: bold;
}
p {
margin: 0;
}
body {
margin: 0;
background-color: #fff;
}
.container {
width: 100%;
max-width: 900px;
margin: auto;
padding: 20px 0;
text-align: left;
}
.header {
align-items: center;
padding: 25px 0;
background-color: #208AEC;
}
.header_logo {
height: 55px;
margin-bottom: 20px;
object-fit: contain;
}
.header_text_bold {
margin-bottom: 3px;
color: rgba(255, 255, 255, 0.9);
font-size: 16px;
font-weight: bold;
}
.header_text {
color: rgba(255, 255, 255, 0.9);
font-size: 15px;
}
.heading {
font-size: 22px;
}
.flex {
display: flex;
}
.flex_between {
display: flex;
justify-content: space-between;
}
.flex_child {
flex: 0 0 45%;
}
.heading_button {
margin-left: 12px;
}
.list_item {
padding-bottom: 15px;
margin-bottom: 15px;
border-bottom: 1px solid rgba(0,0,0,0.06);
text-align: left;
}
.list_item_title {
color: rgba(0,0,0,0.87);
font-size: 17px;
}
.list_item_description {
color: rgba(0,0,0,0.5);
font-size: 15px;
}
Conclusion
At the end of this guide, you learned how to retrieve the current Parse user data from local storage on React. In the next guide, we will show you how to enable your user to reset his password.