In the fourth chapter of the tutorial on building an end-to-end dapp on Aptos, you will be learning to fetch data from chain.
Our UI logic relies on whether the connected account has created a todo list. If the account has created a todo list, our app should display that list; if not, the app should display a button offering the option to create a new list.
For that, we first need to check if the connected account has a TodoList
resource. In our smart contract, whenever someone creates a todo list we create and assign a TodoList
resource to their account.
To fetch data from chain, we can use the Aptos TypeScript SDK. The SDK provides classes and functions for us to easily interact and query the Aptos chain.
To get started:
Stop the local server if running.
In the client
directory, run: npm i @aptos-labs/ts-sdk
In the App.tsx
file, import the Aptos
class like so:
import { Aptos } from "@aptos-labs/ts-sdk";
The TypeScript SDK provides us with a Aptos
class which is the main entry point into Aptos's API. By initializing Aptos
we can query the Aptos chain.
tip
Read more about the Aptos
class in the Aptos TypeScript SDK docs.
In the App.tsx
file, add:
const aptos = new Aptos();
This will initialize a Aptos
instance for us.
note
By default, Aptos
will interact with the devnet
network, to set up a different network, we can use AptosConfig
class.
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";const aptosConfig = new AptosConfig({ network: Network.MAINNET });const aptos = new Aptos(aptosConfig);
Our app displays different UIs based on a user resource (i.e if a user has a list ⇒ if a user has a TodoList
resource). For that, we need to know the current account connected to our app.
Import wallet from the wallet adapter React provider:
import { useWallet } from "@aptos-labs/wallet-adapter-react";
Extract the account object from the wallet adapter:
function App ( const { account } = useWallet(); ...)