wagmi best practice to read from a contract in loop #2278
Unanswered
BramMathijssen
asked this question in
Q&A
Replies: 3 comments
-
|
Maybe you should use export const useContractReadLoop = (
membersList,
contract,
abi,
functionName
) => {
const [list, setList] = useState([]);
const { data, isError, isLoading } = useContractReads({
contracts:list.map((item) =>({
address: contract,
abi: abi,
...item,
}))
})
return data;
}; |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
Now with
This solution is working for me. Do checkout this example. "use client";
import { useReadContract, useReadContracts } from "wagmi";
import SimpleVotingAbi from "@/abis/SimpleVoting.json";
import { BallotType, ConfigType } from "./CreateBallot";
import { useState } from "react";
import configData from "@/config.json";
import { getChainId } from "@wagmi/core";
import { config } from "@/config";
import { Abi } from "viem";
const Config: ConfigType = configData as ConfigType;
export function ReadContract() {
const [Ballots, setBallots] = useState<BallotType[]>([]);
const [isLoadingBallots, setIsLoadingBallots] = useState(true);
const chainId = getChainId(config);
const contractAddress = Config[chainId]?.simpleVoting
.address as `0x${string}`;
console.log("contractAddress ;", contractAddress);
const { data: numberOfBallots, isLoading: numberOfBallotsLoading } =
useReadContract({
abi: SimpleVotingAbi,
address: contractAddress,
functionName: "getNumberofBallots",
});
const contractCalls = Array.from({ length: Number(numberOfBallots) }).map(
(_, index) => ({
abi: SimpleVotingAbi as Abi,
address: contractAddress,
functionName: "getBallotByIndex",
args: [index],
})
);
const { data: ballots, isLoading: ballotsLoading } = useReadContracts({
contracts: contractCalls,
});
if (numberOfBallotsLoading) {
return <div>Loading..</div>;
}
return <div>Ballots : {numberOfBallots?.toString()}</div>;
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
You can use the version that is not a hook |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Does wagmi offer any kind of options to call a contract function with variable args in a loop? I want to call a mapping from my smart contract which I want to iterate over by key, but I can't find any solution offered by wagmi to do this.
I've written this custom hook which does work, but it isn't ideal since React gives me a linter warning:
React Hook "useContractRead" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render.What are the best practices for calling a function / reading a contract in a loop using wagmi? My current code looks as follows
Beta Was this translation helpful? Give feedback.
All reactions