Skip to content

Instantly share code, notes, and snippets.

@jonahallibone
Created March 24, 2020 22:59
Show Gist options
  • Save jonahallibone/f144d94d1165654da969e4854fa53718 to your computer and use it in GitHub Desktop.
Save jonahallibone/f144d94d1165654da969e4854fa53718 to your computer and use it in GitHub Desktop.
import React, { useContext, useRef, useMemo } from "react";
import {
ApolloClient,
ApolloProvider,
HttpLink,
InMemoryCache
} from "@apollo/client";
import { setContext } from "apollo-link-context";
import { BrowserRouter as Router } from "react-router-dom";
import AppContext from "./AppContext";
import App from "./App";
const httpLink = new HttpLink({
uri: "/.netlify/functions/graphql"
});
const ApolloWrapper = () => {
const { silentAuth } = useContext(AppContext);
const tokenRef = useRef(null);
const authLink = useMemo(
() =>
setContext(async (_, { headers }) => {
if(!tokenRef.current) {
const { idToken } = await silentAuth();
tokenRef.current = idToken;
}
return {
headers: {
...headers,
authorization: tokenRef.current ? `Bearer ${tokenRef.current}` : ""
}
};
}),
[silentAuth]
);
const client = useMemo(() => {
return new ApolloClient({
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
});
}, [authLink]);
return (
<ApolloProvider client={client}>
<Router>
<App />
</Router>
</ApolloProvider>
);
};
export default ApolloWrapper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment