Joey Yi Zhao
Joey Yi Zhao

Reputation: 42444

How to inject `apollo client` through react context via `contextType` instead of consumer?

I am looking for contextType way to inject apollo client to a react component. I know below code works but it requires a few lines of code.

import { ApolloConsumer } from "react-apollo";

const WithApolloClient = () => (
  <ApolloConsumer>
    {client => "We have access to the client!" /* do stuff here */}
  </ApolloConsumer>
);

React doc(https://reactjs.org/docs/context.html#dynamic-context) introducers a new way to inject context without using consumer. It is done by set contextType for the component class. I wonder how I can use contextType to inject apollo client? What contextType should I use?

Upvotes: 1

Views: 625

Answers (1)

Joey Yi Zhao
Joey Yi Zhao

Reputation: 42444

Ok I found I can import ApolloContext from react-apollo to solve it like below:

import { ApolloContext } from 'react-apollo';

const HomeContainer = (props: HomeProps) => {
  const context = useContext(ApolloContext);
  return <Home {...props} />;
}

Upvotes: 4

Related Questions