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
  }, []);

2 Answers 2

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

0

may you can use simple rpc provider rather sockets I was having same issue I resolved it by using rpc provider infura and only call a single event in useffect hook you can make multiple hooks make sure state you are changing is mounted and rendering only through one useEffect

Provider = new ethers.providers.JsonRpcProvider(`https://polygon-mumbai.infura.io/v3/${INFURA_ID}`)
const Dog = new ethers.Contract(
          DogAdress,
          NFTDog.abi,
          Provider);

useEffect(()=>{
Dog.on("event1" function)


})

useEffect(()=>{
Dog.on("event2" function)


})

the reason behind this problem is sometime we are rfendering multiple time or trying to change a unmounted state

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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