Search code examples
blockchainweb3jstrufflemetamaskganache

How can I get the data stored in blockchain and then display on webpage?


I am using metamask, ganache, truffle and web3js to develop a system that registers the user's details and keep them in the blockchain. I have successfully deployed the smart contract and stored the user's details in the blockchain. But then, how can I extract the data from the blockchain and display the data (e.g full name and country) on the webpage? Is it possible to do this by using the block number or transaction hash (tx hash)? I have also managed to display the current block number of blockchain onto the webpage using a web3 function, which is:

web3.eth.getBlockNumber(function (error, result)


Solution

  • You can use truffle to interact with your smart contract or retrieve data from it.

    Let's say I have a contract looks like this:

    contract MetaCoin {
        mapping (address => uint) balances;
    
        ...
    
        function getBalance(address addr) public view returns(uint) {
            return balances[addr];
        }
    }
    

    You can call function getBalance in your javascript code to get the balance of an address with the following code:

    // Interact with truffle contract instance
    let balance = await instance.getBalance(accounts[0])
    balance.toNumber()
    

    Here is a more detailed version: interacting with your contract

    Here is a brief tutorial on how to build a dapp with truffle: Pet Shop