import React, { ReactNode, createContext, useContext, useState, useMemo, } from "react"; import { ApolloClient, ApolloLink, InMemoryCache, ApolloProvider, HttpLink, from, } from "@apollo/client"; import { API_URI } from "@env"; type Props = { children: ReactNode; }; export const AuthHeaderContext = createContext< | { authHeader: { key: string; value: string }; setAuthHeader: React.Dispatch< React.SetStateAction<{ key: string; value: string }> >; } | undefined >(undefined); // Hook to use the auth header context export const useAuthHeader = () => { const context = useContext(AuthHeaderContext); if (!context) { throw new Error("useAuthHeader must be used within a ClientProvider"); } return context; }; export const ClientProvider: React.FC = ({ children }) => { const [authHeader, setAuthHeader] = useState({ key: "", value: "" }); const httpLink = new HttpLink({ uri: API_URI || "https://api-dev.railbird.ai/graphql", }); const cache = new InMemoryCache({}); const authMiddleware = new ApolloLink((operation, forward) => { 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({ // Chain the middleware with the httpLink link: from([authMiddleware, httpLink]), cache: new InMemoryCache(), }), [authHeader], ); return ( {children} ); };