I am trying to display the events that are emitted from a function in my smart contract to the front end of my dApp, and I feel like I am missing a step in the connection process with my dApp.
I've programmed it so the button handles the function on click, and that button should print the stringified JSON data to my console, but it's not. I'm also not getting any specified errors to my console either, so that makes me think the provider isn't properly connected.
Is there a step I am missing somewhere else, or am I just not properly connecting to a provider?
Here is my react code:
import { ethers } from "ethers";
// Importing the ABI
import CrowdGaming from "../artifacts/contracts/CrowdGaming.sol/CrowdGaming.json";
//Contract address
const contractAddress = "0x882978f7Afef5bc38c73461f4Bf096e5dF03Ef5C";
const provider = new ethers.providers.WebSocketProvider(
`wss://eth-goerli.g.alchemy.com/v2/${process.env.REACT_APP_ALCHEMY_API}`
);
const contract = new ethers.Contract(
contractAddress,
CrowdGaming.abi,
provider
);
// Launch Event
async function getLaunchEvents() {
try {
contract.on(
"Launch",
(id, owner, title, goal, description, startAt, endAt) => {
let launchEvent = {
id: id,
owner: owner,
title: title,
goal: ethers.utils.formatEther(goal),
description: description,
startAt: startAt,
endAt: endAt,
};
// Print to console
console.log(JSON.stringify(launchEvent));
}
);
} catch (err) {
console.log(err);
}
}
const AllCampaigns = () => {
return (
<div className="h-screen">
<button onClick={getLaunchEvents}> Launch Events</button>
</div>
);
};
export default AllCampaigns;
And here is the event code within the contract:
event Launch(uint id, address indexed owner, string title, uint goal, string description, uint256 startAt, uint256 endAt);
The event is properly emitted on Goerli Etherscan so I know the contract is working as intended. If anyone has any guess or ideas, that would be awaesome!