Add ApolloLink to inject auth headers

This commit is contained in:
Ivan Malison 2024-02-03 18:10:58 -07:00
parent 473d79a32d
commit e69f9dc2d8
2 changed files with 45 additions and 4 deletions

View File

@ -1,5 +1,8 @@
root = true root = true
[*.tsx]
indent_style = tab
[*.json] [*.json]
end_of_line = lf end_of_line = lf
charset = utf-8 charset = utf-8

View File

@ -1,6 +1,7 @@
import React, { ReactNode } from "react"; import React, { ReactNode, createContext, useContext, useState } from "react";
import { import {
ApolloClient, ApolloClient,
ApolloLink,
InMemoryCache, InMemoryCache,
ApolloProvider, ApolloProvider,
HttpLink, HttpLink,
@ -12,17 +13,54 @@ type Props = {
children: ReactNode; children: ReactNode;
}; };
const AuthHeaderContext = createContext();
export const AuthHeaderProvider = ({ children }) => {
const [authHeader, setAuthHeader] = useState({ key: "", value: "" });
return (
<AuthHeaderContext.Provider value={{ authHeader, setAuthHeader }}>
{children}
</AuthHeaderContext.Provider>
);
};
// Hook to use the auth header context
export const useAuthHeader = () => useContext(AuthHeaderContext);
const ClientProvider: React.FC<Props> = ({ children }) => { const ClientProvider: React.FC<Props> = ({ children }) => {
const httpLink = new HttpLink({ const httpLink = new HttpLink({
uri: API_URI, uri: API_URI,
}); });
const cache = new InMemoryCache({}); const cache = new InMemoryCache({});
const client = new ApolloClient({ const { authHeader } = useAuthHeader();
link: from([httpLink]),
cache: cache, const authMiddleware = new ApolloLink((operation, forward) => {
// Retrieve auth key and value from context
const { key, value } = authHeader;
if (key && value) {
operation.setContext({
headers: {
[key]: value,
},
});
}
return forward(operation);
}); });
// We use useMemo to avoid recreating the client on every render
const client = useMemo(
() =>
new ApolloClient({
link: from([authMiddleware, httpLink]), // Chain the middleware with the httpLink
cache: new InMemoryCache(),
}),
[authHeader],
);
return <ApolloProvider client={client}>{children}</ApolloProvider>; return <ApolloProvider client={client}>{children}</ApolloProvider>;
}; };