useContractRead
Generic hook for reading any data from a smart contract via it’s function/view/variable name.
import { useContractRead } from "@thirdweb-dev/react";
const { data, isLoading, error } = useContractRead(contract, "getName");
Usage
Provide your smart contract instance from useContract
and a function name as the arguments.
For example, to read the value of a view
on your smart contract called getName
you would do the following:
import { useContractRead, useContract } from "@thirdweb-dev/react";
// Your smart contract address
const contractAddress = "{{contract_address}}";
function App() {
const { contract } = useContract(contractAddress);
const { data, isLoading, error } = useContractRead(contract, "getName");
}
If you have cached the ABI of your smart contract using thirdweb generate
,
the functionName
and args
parameters are strongly typed according to your smart contract’s ABI.
Configuration
Function Name
Function Name
The function name you provide should be the name of the function in your smart contract.
This can be any function, view, variable, etc. that does not require a transaction to occur.
import { useContractRead, useContract } from "@thirdweb-dev/react";
// Your smart contract address
const contractAddress = "{{contract_address}}";
function App() {
const { contract } = useContract(contractAddress);
const { data, isLoading, error } = useContractRead(
contract,
"myContractFunction",
);
}
Arguments
Arguments
If your function requires arguments, pass them as additional arguments to the hook.
import { useContractRead, useContract, Web3Button } from "@thirdweb-dev/react";
// Your smart contract address
const contractAddress = "{{contract_address}}";
function App() {
const { contract } = useContract(contractAddress);
// Read contract with arguments
const { data, isLoading, error } = useContractRead(
contract,
"getName",
["arg1", "arg2"],
);
if (error) {
console.error("failed to read contract", error);
}
return (
<div>{isLoading ? <p>Loading...</p> : <p>Contract Name: {data}</p>}</div>
);
}
Call Overrides
Call Overrides (optional)
If you provide an additional argument to the hook, it will be used as the CallOverrides
object send with your request.
To include the sender's address (msg.sender) when calling view functions within your smart contract, include the property {from: 0X123} passing the relevant address.
import { useContractRead, useContract, Web3Button } from "@thirdweb-dev/react";
// Your smart contract address
const contractAddress = "{{contract_address}}";
function App() {
const { contract } = useContract(contractAddress);
// Read contract with arguments
const { data, isLoading, error } = useContractRead(
contract,
"getName",
// function arguments
["arg1", "arg2"],
// Final argument is the call overrides
{
blockTag: 123,
from: "0x123",
},
);
if (error) {
console.error("failed to read contract", error);
}
return (
<div>{isLoading ? <p>Loading...</p> : <p>Contract Name: {data}</p>}</div>
);
}