...

/

GraphQL Caching of Queries with Apollo Client in React

GraphQL Caching of Queries with Apollo Client in React

In this lesson, you will implement the Organization Component and learn how to cache queries using GraphQL with Apollo Client in React.

In this lesson, we will introduce React Router to show two separate pages for your application. At the moment, we are only showing one page with a Profile component that displays all your repositories. We want to add another Organization component that shows repositories by an organization, and there could be a search field as well, to look up individual organizations with their repositories on that page. Let’s do this by introducing React Router to our application. If you haven’t used React Router before, make sure to conduct the exercises of this lesson to learn more about it.

In your src/constants/routes.js file, you can specify both routes you want to make accessible by React Router. The ORGANIZATION route points to the base URL, while the PROFILE route points to a more specific URL.

Press + to interact
export const ORGANIZATION = '/';
export const PROFILE = '/profile';

Next, map both routes to their components. The App component is the perfect place to do it because the two routes will exchange the Organization and Profile components based on the URL there.

Press + to interact
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Profile from '../Profile';
import Organization from '../Organization';
import * as routes from '../constants/routes';
import './style.css';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<div className="App-main">
<Route
exact
path={routes.ORGANIZATION}
component={() => (
<div className="App-content_large-header">
<Organization />
</div>
)}
/>
<Route
exact
path={routes.PROFILE}
component={() => (
<div className="App-content_small-header">
<Profile />
</div>
)}
/>
</div>
</div>
</Router>
);
}
}
export default App;

The Organization component wasn’t implemented yet, but you can start with a functional stateless component in the src/Organization/index.js file, that acts as a placeholder to keep the application working for now.

Press + to interact
import React from 'react';
const Organization = () => <div>Organization</div>;
export default Organization;

Since you mapped both routes to their respective components, so you want to implement navigation from one route to another. For this, introduce a Navigation component in the App component.

Press + to interact
...
import Navigation from './Navigation';
import Profile from '../Profile';
import Organization from '../Organization';
...
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Navigation />
<div className="App-main">
...
</div>
</div>
</Router>
);
}
}
export default App;

Next, we’ll implement the Navigation component, which is responsible for displaying the two ...