Last active
December 8, 2021 15:39
-
-
Save schmidsi/77922bd8331bae94cee933657f64415e to your computer and use it in GitHub Desktop.
Block polling pattern examples with fallback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let timeout; | |
const refresh = () => { | |
window.clearTimeout(timeout); | |
// do query | |
timeout = window.setTimeout(() => { | |
refresh(); | |
}, 10 * 1000); | |
}; | |
ethereum.on("chainChanged", () => window.location.reload()); | |
ethereum.on("accountsChanged", refresh); | |
ethereum | |
.request({ | |
method: 'eth_subscribe', | |
params: ['newHeads'], | |
}) | |
.then((subscriptionId) => { | |
ethereum.on('message', (message) => { | |
if (message.type === 'eth_subscription') { | |
const { data } = message; | |
if (data.subscription === subscriptionId) { | |
if ('result' in data && typeof data.result === 'object') { | |
refresh(); | |
console.log(`New block ${block.number}:`, block); | |
} else { | |
console.error(`Something went wrong: ${data.result}`); | |
} | |
} | |
} | |
}); | |
}) | |
refresh(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql, useQuery } from "@apollo/client"; | |
import { useWeb3React } from "@web3-react/core"; | |
import { useEffect } from "react"; | |
import { useAppContext } from "../components/AppContextWrapper"; | |
export const useLastMints = () => { | |
const { library } = useWeb3React(); | |
const { getReadContract } = useAppContext(); | |
const { loading, error, data, refetch } = useQuery( | |
gql` | |
{ | |
tokens(first: 5) { | |
id | |
owner { | |
id | |
} | |
uri | |
audioBase64 | |
svgBase64 | |
} | |
} | |
`, | |
{ pollInterval: 60 * 1000 } // Fallback polling every minute | |
); | |
useEffect(() => { | |
if (library) { | |
const contract = getReadContract(library); | |
contract.on("Mint", refetch); | |
return () => { | |
contract.off("Mint", refetch); | |
}; | |
} | |
}, [library, getReadContract, refetch]); | |
const nfts = data?.tokens || []; | |
return { loading, error, nfts }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using a standard eth provider: https://eips.ethereum.org/EIPS/eip-1193#events like: https://docs.metamask.io/guide/ethereum-provider.html#table-of-contents