4

In my Next.js project, in the app.jsx file, I've set up a websocket and listeners for our 4 events.

However, when one of these events fires, it logs in Discord 3 or more times and I can't seem to figure out why.

Maybe something in Next is loading this multiple times and attaching a listener to a socket multiple times? Any ideas here?

Thanks

  useEffect(() => {
    // Socket connections
    const socket = new ethers.providers.AlchemyWebSocketProvider(1, process.env.ALCHEMY)
    const contract = new ethers.Contract(CONTRACT, ABI, socket)

    contract.on('Minted', (address, amount) => {
        const text = `${address} minted ${amount} NFTs!`
        logInSalesDiscord(text)
            .then((success) => console.log(success))
    });

    contract.on('PromoMinted', (mintedTo, amount) => {
        const text = `We minted ${amount} NFTs to ${mintedTo}`
        logInSalesDiscord(text)
        .then((success) => console.log(success))
    })

    contract.on('FundsWithdrawn', (amount) => {
        const text = `${ethers.utils.formatUnits(amount, 18)} ETH were withdrawn to our Gnosis Safe`
        logInEventsDiscord(text)
            .then((success) => console.log(success))
    })

    contract.on('FallbackHit', (whoSent, amount) => {
        const text = `The fallback function was sent ${ethers.utils.formatUnits(amount, 18)} by ${whoSent}`
        logInSalesDiscord(text)
            .then((success) => console.log(success))
    })
    // End sockets
  }, []);

1 Answer 1

0

At first remove all listeners during unmount,

  contract.on('FallbackHit', (whoSent, amount) => {
        const text = `The fallback function was sent ${ethers.utils.formatUnits(amount, 18)} by ${whoSent}`
        logInSalesDiscord(text)
            .then((success) => console.log(success))
    })
    return () => {
      contract.removeAllListeners();
    };
  }, []);

Second, prevent multiple rendering

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.