Apollo Consumer

Nearly all of the code that we have written can stay as it was in the previous section. We just need to remove the UserProvider from the App class, because it is not needed anymore for the Apollo Consumer.

Open up the user.js in the context folder and replace the contents with the following code:

import React, { Component } from 'react';
import { ApolloConsumer } from 'react-apollo';

export class UserConsumer extends Component {
render() {
const { children } = this.props;
return (
<ApolloConsumer>
{client => {
// Use client.readQuery to get the current logged in user.
const user = {
username: "Test User",
avatar: "/uploads/avatar1.png"
};
return React.Children.map(children, function(child){
return React.cloneElement(child, { user });
});
}}
</ApolloConsumer>
)
}
}

As you can see, we import the ApolloConsumer from the react-apollo package. This package enables us to get access to the Apollo Client that we set up in Chapter 4, Integrating React into the Back end with Apollo.

The problem we have here is that we do not have a CurrentUser query, which would respond with the logged-in user from the GraphQL; so, we are not able to run the readQuery function. You would typically run the query against the internal cache of Apollo, and be able to get the user object easily. Once we have implemented authentication, we will fix this problem.

For now, we will return the same fake object as we did with the React Context API. The Apollo Client replaces the Provider that we used with the React Context API.

I hope that you can understand the difference between these two solutions. In the next chapter, you will see the ApolloConsumer in full action, when the user query is established and can be read through the client of its cache.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.96