handleSubmit 中没有调用钩子

hook is not being called in handleSubmit

我有一个要在 handleSubmit 中调用的挂钩。这个钩子的数据会传给另一个钩子,根据第二个钩子的响应,我想推送不同的页面。

第一个钩子:

const write = useContractWrite(
      {
        addressOrName: Address,
        contractInterface: Interface,
      },
      'entry',
      { 
        args: [firstAnswer.trim().toLowerCase(), secondAnswer.trim().toLowerCase()],
        overrides: { 
          value: ethers.utils.parseEther("0.01") 
       }
      }
    )

Documentation for useContractWrite

我还有一个依赖useContractWrite hook数据的hook:

const waitForTransaction = useWaitForTransaction({
      wait: write!.data?.wait,
      onSettled(data, error) {
        console.log("Settled", { data })
      }
    });

Docs for useWaitForTransaction

最后,我的 handleSubmit:

async function handleSubmit() {
      if (firstAnswer.length == 0 || secondAnswer.length == 0) {
        setInputError(true);
      }
      else {
        setInputError(false);

        //write
        const txn = write;
        // console.log(write + "writeData")

        //wait            
        // console.log(waitForTransaction.data + "waitData")
      }
    }

我确信可以轻松解决此问题,但我看不出问题出在哪里。我已按照文档进行操作,但它不起作用。

根据文档,waitForTransaction 是整个 return 值,而不是 returned 值的 属性,因此您需要删除卷曲牙套。

const waitForTransaction = useWaitForTransaction({...})

你会遇到的另一个问题是钩子不能有条件地调用,所以这样做在hook-land

中是非法的
else {
  ...
  // cannot do this inside if () {} else {}
  const waitForTransaction = useWaitForTransaction({...})
}

查看 wagmi 示例,我会像这样添加 handleSubmit

import { useContractWrite, useWaitForTransaction } from 'wagmi'

function App() {

  const [inputError, setInputError] = useState(false)

  const contractWrite = useContractWrite(
    {
      addressOrName: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1',
      contractInterface: wagmigotchiABI,
    },
    'feed',
  )

  const handleSubmit = () => {
    const hasError = firstAnswer.length == 0 || secondAnswer.length == 0;
    setInputError(hasError)
    if (!hasError) {
      contractWrite.write()       // call write method of contract
    }
  }

  // use with conditional inside hook call
  const waitForTransaction = useWaitForTransaction({
    wait: contractWrite.data?.wait 
  })
}