Background
I have a web3 dapp that is currently minting NFT’s correctly without issue.
When I call this mintNFT function, it sends a single transaction and succeeds each time.
I am adding functionality to “merge” two NFT’s using a contract function.
When I tie this new mergeTwoNFT to a button click, it seems to run the function multiple times as I get a metamask request for multiple transactions at once, sometimes 10-20 transactions to accept/reject at one time.
The first of these transactions will succeed however of course the remainder will fail because the tokenID 1/2 variables that we are merging are no longer owned by this user.
Request
I’m stuck on this sending multiple transactions. If I change the function call to be automatically run when the user “checks” two images they own, instead of using a button click event, it seems to work better without duplicate transactions but I don’t want this function to be called automatically upon two images being selected in case they’d like to undo it.
Code
This is my merge function. I have the same function for minting which works.
In the below example, alts
is referencing the “checked” images on the UI that the user has selected.
async function mergeNFTs() {
const alts = $("#NFTGallery2 > li > input:checked + label img").map(function() {
return this.alt
}).get();
var nftChosen1 = alts[0]
var nftChosen2 = alts[1]
setFeedback(`Merging your ${nftChosen1} and ${nftChosen2}...`);
setClaimingNft(true);
dispatch(fetchData(blockchain.account));
myContract.methods
.mergeTwoNFT(nftChosen1, nftChosen2)
.send({
from: blockchain.account
})
.once('error', (err) => {
console.log(err);
setFeedback(
"Sorry, something went wrong when Merging your NFT's please try again later."
);
setClaimingNft(false);
})
.then((receipt) => {
var tokenId = receipt.events.Transfer[2].returnValues.tokenId;
console.log(
'Your new NFT ID is: ' + receipt.events.Transfer[2].returnValues.tokenId
);
setFeedback(
`WOW, the ${CONFIG.NFT_NAME} #${tokenId} is yours!`
);
myContract.methods
.tokenURI(tokenId)
.call()
.then(function (res) {
$.getJSON(res, function (data) {
const mintedNFTImage = `
<div class="layeredImg "sc-gKseQn gTjrPu" id="mintedImage">
<img id="imgbg" src="${data.image}"/>
</div>
<br>
`;
document.getElementById('NFTEmbed').innerHTML = mintedNFTImage;
});
})
.catch(function (err) {
console.log(err);
});
setClaimingNft(false);
dispatch(fetchData(blockchain.account));
getData();
getData2();
});
};
<button id="mergingButton" onclick=mergeNFTs() class="">MERGE</button>