Overlay With Login

This example shows how to work with the overlay through the new Core Login API.

As an example let's connect and disconnect an Ethereum network account using a button in the overlay.

Here is the initial code for this example: ex17-overlay-login-exercise.

Dapplet#

More details about the useState and onAction methods can be found in Shared State section.

LP: 1. Add the 'useState' method to the overlay#

Add the method to overlay initialization. The state will transfer the account address from the dapplet to the overlay.

private overlay = Core.overlay<IBridge>({ name: 'overlay', title: 'Exercise 17' })
.useState(this.state)

LP: 2. Declare the API in the overlay#

dapplet/src/api.ts contains the functions that will be available in the overlay.

You can learn more about Core Login API here.

.declare(this.api);

More details about the declare method can be found in Overlays section.

LP: 3. Use the API's function to get the account state#

await this.api.initializeCurrentAccount()

LP: 4. Add the action for the home button#

Add the Core.onAction method. The callback will open the overlay and update the data about the session when the home button is clicked.

1Core.onAction(() => {
2 this.overlay.open()
3 this.api.initializeCurrentAccount()
4})

Overlay#

To implement the overlay part, we use React functional components.

LP: 5. Add the interface for Bridge, with functions#

The Dapplet and the overlay are connected using Bridge and IDappStateProps which are imported from @dapplets/dapplet-overlay-bridge.

1interface IBridge {
2 login: () => Promise<void>
3 logout: () => Promise<void>
4}

LP: 6. Add functions to connect and disconnect the account#

Add functions to App.tsx .

1const handleLogIn = (e: any) => {
2 e.preventDefault()
3 bridge.login()
4}
5
6const handleLogOut = (e: any) => {
7 e.preventDefault()
8 bridge.logout()
9}

LP: 7 Add Login and Logout functions#

Use sharedState to render the component and display the account address.

1return (
2 sharedState && (
3 <div className="wrapper">
4 ...
5 {sharedState.global?.userAccount === '' ? (
6 <button className="login" onClick={handleLogIn}>
7 Log in
8 </button>
9 ) : (
10 <>
11 ...
12 <button className="logout" onClick={handleLogOut}>
13 Log out
14 </button>
15 </>
16 )}
17 </div>
18 )
19)

Here is the result code of the example: ex17-overlay-login-solution.

Run the dapplet:

npm i
npm start

video