javascript 我想编写这个react函数来从thirdweb获取数据并显示

3lxsmp7m  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(120)

帮助我从区块链获取信息并在浏览器中显示。我想知道如何调用这个thirdweb函数的React。下面的代码是用于在我们的系统中创建一个用户的solidity代码。

function createUser(string memory _userId, string memory _fName, string memory _lName, string memory _mobile, string memory _dob, uint256 _age, string memory _nationality, string memory _gender) public {
        if(!chkexisitinguserId(_userId)){
            users[_userId] = User(_fName, _lName, _mobile, _dob, _age,_nationality,_gender);
            noofUser++;
            allUserId[k] = _userId;
            k++;
        }
    }

function getUser(string memory _userId) public view returns (string memory, string memory, string memory, string memory, uint256, string memory, string memory) {
        User memory user = users[_userId];
        return (user.fName, user.lName, user.mobile, user.dob, user.age, user.nationality, user.gender);
    }

以下代码是与智能合约交互的第三个web库代码,存储在refer.js文件中。

import { useContract, useContractWrite } from "@thirdweb-dev/react";

export default function Component() {
  const { contract } = useContract("0xBB417720eBc8b76AdeAe2FF4670bbc650C3E791f");
  const { mutateAsync: createUser, isLoading } = useContractWrite(contract, "createUser")

  const call = async () => {
    try {
      const data = await createUser([ "John0312", "John", "s", "8090890367", "03-11-2000", 20, "India", "M" ]);
      console.info("contract call successs", data);
    } catch (err) {
      console.error("contract call failure", err);
    }
    
  }
}

export default function Component() {
  const { contract } = useContract("0xBB417720eBc8b76AdeAe2FF4670bbc650C3E791f");
  const { data, isLoading } = useContractRead(contract, "getUser", _userId)
}

智能合约部署在thirdweb中,我正在尝试访问它,但我一直在想如何从app.js调用这个“call”异步函数。

import React, { useEffect } from 'react'
function App(){
const handleclick = async (e) => {
    await call();
  }
 return (
<button onClick={handleclick}>click me</button>
  )
}

export default App

它会生成类似未定义函数call()的错误。

olhwl3o2

olhwl3o21#

我将创建一个新的钩子(useCall.js),它的任务只是示例化useContractuseContractWrite钩子,然后定义call()方法,以便在任何组件中使用。
在这个例子中,call()是钩子返回的唯一的东西,它被 Package 在useCallback中,以确保它只在createUser被定义时才被定义。

export default function useCall() {
  const { contract } = useContract("0xBB417720eBc8b76AdeAe2FF4670bbc650C3E791f");
  const { mutateAsync: createUser, isLoading } = useContractWrite(contract, "createUser")

  const call = React.useCallback(async () => {
    try {
      const data = await createUser([ "John0312", "John", "s", "8090890367", "03-11-2000", 20, "India", "M" ]);
      console.info("contract call successs", data);
    } catch (err) {
      console.error("contract call failure", err);
    }
  }, [createUser]);
  
  return call;
}

现在,在任何组件内部,您都可以使用钩子并获得call()函数:

import useCall from './useCall';

export default function Component() {
  const call = useCall();

  useEffect(() => {
    (async () => {
      await call();
    })();
  }, []);
}

相关问题