useContractRead

Generic hook for reading any data from a smart contract via it’s function/view/variable name.

const { contract } = useContract("{{contract_address}}");
const { data, isLoading, error } = useContractRead(
contract,
"functionName",
args,
);

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.

Example

Provide your smart contract instance from useContract , a function name and the arguments to pass to the function (if any).

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";
function App() {
const { contract } = useContract(contractAddress);
const { data, isLoading, error } = useContractRead(
contract,
"getName",
);
}
function useContractRead(
contract: TContractInstance extends ValidContractInstance
? RequiredParam<TContractInstance<TContractInstance>>
: TContractAddress extends never
? RequiredParam<
BaseContractForAddress<TContractAddress<TContractAddress>>
>
>
: RequiredParam<SmartContract<BaseContract>>,
functionName: RequiredParam<TFunctionName>,
args?: TArgs,
overrides?: CallOverrides,
): UseQueryResult<TReturnType, unknown>;

Parameters

The contract instance of the contract to call a function on

Type

let contract: TContractInstance extends ValidContractInstance
? RequiredParam<TContractInstance<TContractInstance>>
: TContractAddress extends never
? RequiredParam<
BaseContractForAddress<TContractAddress<TContractAddress>>
>
>
: RequiredParam<SmartContract<BaseContract>>;

The name of the function to call in the smart contract. This can be any function, view, variable, etc. that does not require a transaction to occur.

Type

let functionName: RequiredParam<TFunctionName>;

The arguments to pass to the function (if any)

Type

let args: TArgs;

CallOverrides object to 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.

const { data, isLoading, error } = useContractRead(
contract,
"getName",
["arg1", "arg2"],
{
blockTag: 123,
from: "0x123",
},
);

Type

let overrides: CallOverrides;

Returns

let returnType: UseQueryResult<TReturnType, unknown>;

Query result object that includes the data returned by the function call