[SOLVED] How to pass parameters to a contract function dynamically

Hi everyone!

I am having a bad time trying to call to my smart contract inside a loop using useWeb3Contract hook. I am pretty new both to react and smart contract developing so maybe I am doing it all the wrong way.

Well, this is what I have so far:

const {runContractFunction: getByHash} = useWeb3Contract({
        abi: abi,
        contractAddress: address,
        functionName: "getByHash"
    })

And apart from that. I have something like this:

list?.map((item) => {
          getByHash(item.hash).then(.....)  // Call to the function I defined above
}

As far I could understand it is a bad practice (or maybe imposible at all) to use a hook inside a loop, so I am wondering how this could be achieve. I know it must to be a way since it is pretty normal to have mappings in solidity and loop them from the frontend.

In other places I could pass parameters to useContract functions just using state variables as I did here:

const [param1, setParam1] = useState()
const [param2, setParam2] = useState()


const {
        runContractFunction: contractFunctionWithParams,
        isLoading,
        isFetching,
    } = useWeb3Contract({
        abi: abi,
        contractAddress: address,
        functionName: "functionWithParams",
        params: {
            param1,
            param2
        },
    })

But this is not what I need since I want to dynamically call the contract function with the list I loop into.

Any ideas about how can do this?
Thanks in advance! See you!

What do you want to do with the data from getByHash? It would be easier to use the non-hook function if you don’t need the state handling from hooks.

You can also use runContractFunction instead if you only need to call read only functions.

Thanks for the answer! I just need to call a simple read function. I tried with the runContractFunction but because I am working under the hardhat local blockchain, it wont work (unless I am confuse, the hardhat chain is not supported)

I will try the other option you mentioned if it supports hardhat.

useWeb3Contract uses executeFunction (which then uses ethers.js) under the hood. So it should still work with local networks.

Hi! That worked! Thanks a lot!

The solution in case someone has the same problem:

const readOptions = {
                    contractAddress: contract,
                    functionName: "getByHash",
                    abi: abi,
                    params: {
                        hash: match.attributes.hash,
                    },
                };
                const message = await Moralis.executeFunction(readOptions);
````
1 Like