useDid
The useDid hook is a convenient utility for easily extracting and working with specific DID-related information from the session.user object. It simplifies parsing the user object to get commonly needed data like the permanent DID, wallet information, and connected accounts without manual processing.
This hook should be used within a component that is a child of the SessionProvider to ensure it has access to the session context.
How to Use#
To use the hook, import it along with useSession. Call useSession to get the current session state, and then pass the session object to useDid.
Basic Usage
import { useSession } from '@arcblock/did-connect-react';
import { useDid } from '@arcblock/did-connect-react/lib/User';
function UserProfile() {
const { session } = useSession();
const {
did,
walletDid,
connectedDids,
sourceProvider,
connectedAccounts,
} = useDid({ session });
if (!session.user) {
return <p>Please log in to view your DID information.</p>;
}
return (
<div>
<h2>User DID Information</h2>
<p><strong>Permanent DID:</strong> {did}</p>
<p><strong>Wallet DID:</strong> {walletDid || 'N/A'}</p>
<p><strong>Login Method:</strong> {sourceProvider}</p>
<h3>Connected Accounts ({connectedAccounts.length})</h3>
<ul>See all 9 lines
Parameters#
The useDid hook accepts a single object as its parameter.
Return Value#
The hook returns a state object containing various pieces of derived DID information. This object will be updated whenever the session.user object changes.
Standalone Helper Functions#
The useDid hook is built on a set of exported helper functions. If you don't need the reactive state management of a hook and just want to extract a specific piece of information from a user object, you can import and use these functions directly.
Function | Description |
|---|---|
| Extracts the permanent DID from the user object. |
| Extracts the DID of the connected wallet. |
| Retrieves the array of connected accounts. |
| Retrieves an array of DIDs from all connected accounts. |
| Gets the provider used for the initial login. |
| Gets an array of all connected provider names. |
| Finds and returns the complete wallet account object. |
Example: Using a Helper Function#
Direct Function Usage
import { getWalletDid } from '@arcblock/did-connect-react/lib/User/use-did';
import { useSession } from '@arcblock/did-connect-react';
// This approach can be useful inside event handlers or other non-React functions
function handleUserAction() {
const { session } = useSession();
if (session.user) {
const walletDid = getWalletDid(session.user);
console.log('User Wallet DID:', walletDid);
}
}