Get User Account Function
4 min
This documentation provides a detailed explanation of the getAccount function, which handles user account retrieval, login authentication, and interaction with the Ethereum provider. It includes asynchronous operations to ensure smooth and non-blocking user experience.
Function: getAccount
Description
The getAccount function checks if a user is logged in. If not, it initiates the login process. Once the user is logged in, it retrieves the user's Ethereum account. The function also handles loading indicators and emits events upon successful account retrieval.
Code
async function getUserInfo() {
try {
// Create a new User instance
let user = new User();
// Check if the user is logged in
const isLogin_status = await user.islogin();
console.log(isLogin_status, 'isLogin_status');
if (!isLogin_status) {
console.log("login failed, please try again later");
return;
}
// If user is already logged in, interact with Ethereum provider to get account
let account = await user.getAccount();
console.log("getWeb3 account", account);
let userId = await user.getUserId();
console.log("getWeb3 userId", userId);
let result = await user.balance()
if (result && result._balances && result._balances.length) {
let temp = result._balances[0]
let balance = temp / 1000000000000000000n
console.log("getWeb3 balance:",balance)
}
} catch (error) {
console.log(error, "getUserInfo error");
if (error && typeof error == 'string') {
console.log(error);
} else {
console.log(error.message);
}
}
}
Detailed Explanation
- User Object Initialization:
- Creates a new instance of the User object.
- Check Login Status:
- Asynchronously checks if the user is logged in.
- Logs the login status.
- Handle Not Logged In Status:
- Shows a loading toast if the user is not logged in.
- User Info Process:
- Logs the account, userId, balance and any error.
- Error Handling:
- Logs the error.
This setup ensures that the user account status is checked and handled as soon as the component is ready, providing a seamless experience for the user.