Created
March 24, 2020 22:59
-
-
Save jonahallibone/f144d94d1165654da969e4854fa53718 to your computer and use it in GitHub Desktop.
This file contains 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 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