Manage Users
Create User
Developers can call the following login methods to sign in or create a user:
Get Currently Logged-in User
Subscribe to Callback Function for Login State Changes
To get the current user, it is recommended to set a callback function on the Auth
object. This function will be triggered whenever the user's login state changes and will provide the current LoginState
:
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id"
});
const auth = app.auth();
// Set an observer
auth.onLoginStateChanged((loginState) => {
if (loginState) {
// The user is now logged in
} else {
// Not logged in
}
});
Directly Get Current User
You can also use the Auth.currentUser
property to get the currently logged-in user. If the user is not logged in, currentUser
is null
:
const user = auth.currentUser;
if (user) {
// The user is now logged in
} else {
// Not logged in
}
Get User Profile
You can obtain the user's profile information through various properties of the User
object:
const user = auth.currentUser;
let uid, nickName, gender, avatarUrl, location;
if (user) {
// Cloud Base unique user ID
uid = user.uid;
// Nickname
nickName = user.nickName;
// Gender
gender = user.gender;
// Avatar URL
avatarUrl = user.avatarUrl;
// User geographic location
location = user.location;
}
Update User Profile
You can use the User.update
method to update the user's profile information. For example:
const user = auth.currentUser;
user
.update({
nickName: "Tony Stark",
gender: "MALE",
avatarUrl: "https://..."
})
.then(() => {
// User information is updated successfully.
});
Refresh User Profile Information
For a multi-device application, users may update their personal information on one device, and other devices may need to refresh the information:
const user = auth.currentUser;
// Refresh user information.
user.refresh().then(() => {
// After refreshing, the obtained user information will be the latest.
const { nickName, gender, avatarUrl } = user;
});