5

I am building React App and need to use class components.

I have an ApolloClient set up in index.js and it is passing the client to the ApolloProvider. How do I access it in my App component (class component)? Is it even possible? I also have setup Redux and mapped state to props with connect (I thought about using export default withApollo(App) but then I lose state to props mapping with connect()).

Can someone help/explain how to correctly implement apollo-client with react class components? Should I create new ApolloClient in each class component?

index.js

const apolloClient = new ApolloClient({
  uri: "http://localhost:4000/",
  cache: new InMemoryCache(),
});

...

<ApolloProvider client={apolloClient}>
   <App />
</ApolloProvider>

App.js

class App extends Component {
  render() {
...
  }
}

const mapStateToProps = (state) => {
  return {
     ...
  };
};

export default connect(mapStateToProps)(App);

1 Answers1

1

To use ApolloClient in a class-based React component, you will need to make sure that your component is wrapped in an ApolloProvider component. You can use the ApolloConsumer component to get access to the ApolloClient instance.

import React from 'react';
import { ApolloConsumer } from '@apollo/client';

class MyComponent extends React.Component {
  render() {

    return (
      <div>
        <ApolloConsumer>
          {client => (
            <button onClick={() => client.writeData({ data: { isLoggedIn: true } })}>
              Log in
            </button>
          )}
        </ApolloConsumer>
      </div>
    );
  }
}