Guide: Using Tria SDK in a Basic React App
This guide will walk you through integrating the Tria SDK into a basic React application, covering installation, initialization, and usage of various SDK features.
Installation
First, install the Tria SDK in your React project:
npm install @tria-sdk/authenticate-web
or if you're using Yarn:
yarn add @tria-sdk/authenticate-web
Initialization
Create a new file, e.g., triaSDK.js
, to initialize the Tria SDK:
import { AuthManager } from '@tria-sdk/authenticate-web'
const authManager = new AuthManager({
analyticsKeys: {
clientId: 'YOUR_CLIENT_ID',
projectId: 'YOUR_PROJECT_ID',
},
})
// Configure the SDK
authManager.configure({
chain: 'SEPOLIA',
environment: 'mainnet',
})
// Optional: Configure UI
authManager.configureAuthUI({
darkMode: true,
// Add other UI configurations as needed
})
export default authManager
Usage in React Components
Here's an example of how to use the Tria SDK in a React component:
import React, { useState, useEffect } from 'react';
import authManager from './triaSDK';
function TriaAuthComponent() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [account, setAccount] = useState(null);
const [message, setMessage] = useState('');
useEffect(() => {
checkLoginStatus();
setupEventListeners();
}, []);
const checkLoginStatus = () => {
const loggedIn = authManager.isAuthenticated();
setIsLoggedIn(loggedIn);
if (loggedIn) {
setAccount(authManager.getAccount());
}
};
const setupEventListeners = () => {
authManager.addEventListener('TRIA_LOGIN', handleLogin);
authManager.addEventListener('TRIA_LOGOUT', handleLogout);
return () => {
authManager.removeEventListener('TRIA_LOGIN', handleLogin);
authManager.removeEventListener('TRIA_LOGOUT', handleLogout);
};
};
const handleLogout = () => {
setIsLoggedIn(false);
setAccount(null);
};
const handleLogin = (): void => {
console.log("calling handleLogin");
const resp = authManager.getAccount();
setAccount(resp);
console.log(resp);
setIsLoggedIn(true);
};
const login = () => {
authManager.subscribe("LOGIN_SUCCESS", handleLogin);
};
const disconnect = async () => {
try {
await authManager.disconnect();
const handleLogout = (): void => {
console.log("handle logout called!");
};
authManager.subscribe("LOGOUT_SUCCESS", handleLogout);
} catch (error) {
console.error('Disconnect failed:', error);
}
};
const signMessage = async () => {
if (message) {
try {
const result = await authManager.signMessage(message);
console.log('Signed message:', result);
} catch (error) {
console.error('Message signing failed:', error);
}
}
};
const sendTransaction = async () => {
const amount = 0.001; // Example amount
const recipientAddress = '0x...'; // Example recipient address
try {
const result = await authManager.send(amount, recipientAddress);
console.log('Transaction sent:', result);
} catch (error) {
console.error('Transaction failed:', error);
}
};
const writeContract = async () => {
const contractDetails = {
contractAddress: '0x...',
abi: [...], // Your contract ABI
functionName: 'yourFunctionName',
args: [...], // Your function arguments
};
try {
const result = await authManager.writeContract(contractDetails);
console.log('Contract written:', result);
} catch (error) {
console.error('Contract write failed:', error);
}
};
return (
<div>
<h1>Tria Authentication</h1>
{!isLoggedIn ? (
<button onClick={login}>Login</button>
) : (
<div>
<p>Logged in as: {account?.triaName}</p>
<button onClick={disconnect}>Disconnect</button>
<div>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Enter message to sign"
/>
<button onClick={signMessage}>Sign Message</button>
</div>
<button onClick={sendTransaction}>Send Transaction</button>
<button onClick={writeContract}>Write Contract</button>
</div>
)}
</div>
);
}
export default TriaAuthComponent;
Key Points
-
Initialization: The SDK is initialized once and exported from a separate file (
triaSDK.js
) for use across your app. -
State Management: Use React's
useState
to manage login status and user account information. -
Effect Hooks: Use
useEffect
to check login status and set up event listeners when the component mounts. -
Event Listeners: Set up listeners for login and logout events to update the component state accordingly.
-
SDK Methods: Utilize various SDK methods like
login()
,disconnect()
,signMessage()
,send()
, andwriteContract()
for different functionalities. -
Error Handling: Implement try-catch blocks to handle potential errors from SDK method calls.
-
Conditional Rendering: Display different UI elements based on the user's login status.
Best Practices
-
Security: Never hardcode sensitive information like API keys. Use environment variables instead.
-
State Management: For larger applications, consider using state management libraries like Redux or React Context API to manage Tria SDK state globally.
-
TypeScript: If using TypeScript, leverage type definitions provided by the SDK for better type safety and developer experience.
-
Loading States: Implement loading states for asynchronous operations to improve user experience.
-
Error Feedback: Provide user-friendly error messages when operations fail.
-
Cleanup: Remember to remove event listeners in the cleanup function of
useEffect
to prevent memory leaks.
By following this guide, you should be able to successfully integrate the Tria SDK into your basic React application and leverage its authentication and blockchain interaction features.