Reputation: 15
My Problem is:
I have react code that communicates with a smart contract. When i start the server the oncklick function openLong() runs automatically(multiple times-> 3 transactions in Metamask) before i even click the button and when i click the button nothing happens. Why this strange behaviour?
import react, { useState } from 'react';
import { Component } from 'react';
import Web3 from 'web3';
export default function KwentaOptimism() {
let provider = window.ethereum;
let selectedAccount;
if (typeof provider !== 'undefined') {
provider.request({ method: 'eth_requestAccounts' }).then((accounts) => {
selectedAccount = accounts[0];
console.log(`Selected account is ${selectedAccount}`);
});
}
const web3 = new Web3(provider);
async function getNetworkID() {
const networkId = await web3.eth.net.getId();
return networkId;
}
async function loadContract() {
let address = '0x1e28378F64bC04E872a9D01Eb261926717346F98';
let chainlinkFutureContractABI = [
{
constant: false,
inputs: [
{ internalType: 'int256', name: 'marginDelta', type: 'int256' },
],
name: 'transferMargin',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
},
];
var Contract = require('web3-eth-contract');
const web3 = new Web3(provider);
Contract.setProvider(web3);
var chainlinkFutureContract = new Contract(
chainlinkFutureContractABI,
address
);
return await chainlinkFutureContract;
}
async function openLong() {
let linkContract = await loadContract();
linkContract.methods
.transferMargin('100000000000000000000')
.send({ from: '0xce05626e35c053995d4988b75af85e2eb7251b3c' });
}
return (
<div>
<br />
<button onclick={openLong()}>Chainlink Long</button>
</div>
);
}
Upvotes: 0
Views: 126
Reputation: 641
When you do this, you basically call the function. Remove the parenthesis, like on the second line:
<button onclick = {openLong()}>Chainlink Long</button>
<button onClick={openLong}>Chainlink Long</button>
Also, try onClick intead of onclick.
Sometimes you want to pass arguments into a function like this. In those cases, you can do like this:
<button onClick={() => openLong(arguments)}>Chainlink Long</button>
Upvotes: 1