Reputation: 2191
I'm relatively new to react and can't seem to import a client
variable from a context. I have a file called federation.tsx with some code, where I believe this should be the relevant part:
const link = createHttpLink({
uri: process.env.URL,
});
const useApolloClient = (user: User | null) => {
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
Authorization: user?.idToken || "",
},
};
});
return new ApolloClient({
link: authLink.concat(link as any),
cache: cache,
name: "Test",
version: process.env.ANOTHER_URL,
});
};
export const FederationProvider: React.FC = ({children}) => {
const [acc] = useContext(UserContext);
const client = useApolloClient(acc);
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};
And my main app file with the context provider wrapping everything relevant:
function App() {
return (
<div className="App">
<FederationProvider>
<Router>
<Routes/>
</Router>
</FederationProvider>
</div>
);
}
And the file where I try to use it:
import React, {useContext, useEffect} from "react";
import {FederationProvider} from "..src";
export const someComponent(() => {
const [client] = useContext(FederationProvider); // not working
return (<>...</>)
})
Can anyone spot anything obvious that I may have done incorrectly? I'm not sure how to simply just import the client variable.
Upvotes: 3
Views: 932
Reputation: 8318
From the docs, it says to use the client configured via a ApolloProvider
by using the useApolloClient
hook like so :-
const client = useApolloClient();
Docs - https://www.apollographql.com/docs/react/api/react/hooks/#useapolloclient
Upvotes: 3