Web3JS – How to Call a Smart Contract Function in a DApp

dapp-developmentdappsreactweb3js

I am trying to make a DAPP.

I followed this link –

https://medium.com/@takleakshar/how-to-build-a-decentralized-full-stack-app-in-ethereum-and-react-42e63d45a208

This is how my 'Setup.js' looks.

import Web3 from 'web3';

const web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));

const marketplaceContract = new web3.eth.Contract( ABI , 'Smart 
Contract Address', {
from: '0x123....', // default from address
gasPrice: '20000000000' // default gas price in wei, 20 gwei in this 
case
});

//const marketplaceContract = 
web3.eth.contract(MarketABI).at(MarketAddress);
export { marketplaceContract };

As you can see, I am importing the smart contract with the name 'marketplaceContract'.

When I call a function from the smart contract using-

marketplaceContract.addGoods(name, user, age, brand, size, sp);

I get the output as

TypeError: _Setup__WEBPACK_IMPORTED_MODULE_5__.marketplaceContract.addAccounts is not a function

Although, addAccounts is a function.

I don't know if this is a problem with the version of web3. Please kindly help. Is there any other way to call the functions in my React-JS file?

PS – I don't know if I have to put the whole code here. If required, please tell me, I will put both the smart contract and the React file here. I didn't put it because it's very big.
Please don't start scorning me.

EDITS

When I have a .call() function, it works well. But when I have a function that stores some data in a struct datatype in the Blockchain, it does not work.
I used .send({from: accounts[0]}) for that function. Then the error pops up

Unhandled Rejection (TypeError): Cannot read property 'match' of undefined

I searched for this error. I deleted my package-lock.json file and node_modules and then did npm install.
Still, I get the same error.
How should I proceed?

Best Answer

Please check https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#id10 . You have to add .methods to your contract instance and then call the smart contract method.

Related Topic