0

I need to get data on all transactions on an L2 protocol. I'm using the useContractRead hook.

const contractRead = useContractRead({
    address:  address,
    abi: ContractABI,
    functionName: 'functionName'
})
console.log(contractRead);

console.log(contractRead);

The data returned is undefined. enter image description here

1 Answer 1

0

Easiest way for reusability is to first set up a json file with address and abi and a config for the contract:

import config from '../path/to/contractConfig.json'

const contractConfig = {
  address: config.address,
  abi: config.abi
};

Now you don't have to re-write the address and abi in every single function call you're making.

Then you need to identify what type of data you're receiving from the useContractRead() hook, as per the wagmi documentation:

const { data: functionData } = useContractRead({
  ...contractConfig,
  functionName: 'functionName',
});

Then you can take that data and use elsewhere, passing the functionData variable in as needed.

However, by default, the useContractRead() can lead to attempting to fetch the data every block, which can lead to rate-limiting if you're running directly through RPC providers, so it's a good idea to write a custom hook to handle that data before you pass it to your app.

Here's an example of wrapping two reads together with a check to ensure the contract doesn't try to read every single block. You can do the same with just one instance of useContractRead:

const handleContractReads = () => {
  const { data: dataOne } = useContractRead({
    ...contractConfig,
    functionName: 'functionOne',
    watch: true,
    onError: (err) => { console.error(err) }
  });
  const { data: dataTwo } = useContractRead({
    ...contractConfig,
    functionName: 'functionTwo',
    watch: true,
    onError: (err) => { console.error(err) }
  });
  // Perform a check before fetching contract data.
  if (!someCondition) return null;
  SetVarOne(dataOne);
  setVarTwo(dataTwo);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.