Lesson 10 - "A Challenge To You" (automatically polling for Raffle events) #5631
vvinteresting
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I had a very hard time figuring out how to make this in a performant way, so I thought I would share how I made this work locally.
instantiate provider in state. This was crucial for me, because otherwise
provider
kept getting re-defined on re-render, which would occur constantly due to updates to other elements in the component. This would result in looping polling requests to the chain and was hugely resource intensive.const [ provider, setProvider ] = useState(new ethers.providers.JsonRpcProvider(process.env.RPC_URL!));
instantiate the contract:
const Lottery = new ethers.Contract(lotteryAddress, abi as ContractInterface, provider);
listen for the events, and update state when appropriate:
There are still some issues: Events are sometimes received in duplicate, and events from the past also fire Lottery.once() sometimes (this is a known issue with Ethers v5, see here: ethers-io/ethers.js#2353). Additionally, fetchUI sets state a dozen times in a row, despite first checking if the previous value and the new value differ before setting. This must be a quirk with React's state that I don't yet understand.
Regardless, this works to update the UI based on contract events alone, instead of relying on user interaction to trigger them. Here's my code:
https://github.com/vvinteresting/fcc-solidity/blob/8b7bcad861264fcc2c6c325f8af435d0a9bf97a6/nextjs-lottery/components/LotteryEntrance.tsx
Beta Was this translation helpful? Give feedback.
All reactions