Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Last active January 21, 2020 20:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulRBerg/1bc52b0031f491034e383b282370e8f7 to your computer and use it in GitHub Desktop.
Save PaulRBerg/1bc52b0031f491034e383b282370e8f7 to your computer and use it in GitHub Desktop.
Use Apollo Client with Hooks and web3-react
import React, { useMemo } from "react";
import { ApolloClient } from "apollo-client";
import { ApolloProvider } from "@apollo/react-hooks";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { useWeb3React } from "@web3-react/core";
const CHAIN_IDS_TO_NAMES = {
1: "mainnet",
3: "ropsten",
4: "rinkeby",
5: "goerli",
42: "kovan",
};
function createClient(chainName = "") {
/* By default, we display the data on mainnet */
let uri;
if (!chainName || chainName === "mainnet") {
uri = process.env.REACT_APP_APOLLO_HTTP_URL;
} else {
uri = process.env.REACT_APP_APOLLO_HTTP_URL + "-" + chainName;
}
return new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({ uri }),
});
}
export default function ApolloReactManager({ children }) {
const { chainId } = useWeb3React();
const client = useMemo(() => {
const chainName = CHAIN_IDS_TO_NAMES[chainId] || "";
return createClient(chainName);
}, [chainId]);
return <ApolloProvider client={client}>{children}</ApolloProvider>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment