Skip to content

Instantly share code, notes, and snippets.

@schmidsi
Last active December 8, 2021 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmidsi/77922bd8331bae94cee933657f64415e to your computer and use it in GitHub Desktop.
Save schmidsi/77922bd8331bae94cee933657f64415e to your computer and use it in GitHub Desktop.
Block polling pattern examples with fallback
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();
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 };
};
@schmidsi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment