DEV Community

Cover image for First steps in building app with React, Strapi & Apollo GraphQL
Semir Teskeredzic
Semir Teskeredzic

Posted on

First steps in building app with React, Strapi & Apollo GraphQL

I have to say I fell in love with Strapi from the day I found it. For all of those who never heard of Strapi be sure to checkout Strapi.io.

As per Strapi.io:

Strapi is the leading open-source Headless CMS. Strapi gives developers the freedom to use their favorite tools and frameworks while allowing editors to easily manage their content and distribute it anywhere.

And it just connects with anything, since I love working with React as well I had to give it a try. Instead of using REST I went with GraphQL and Apollo since it is steady becoming an essential tool in building scalable and performant web applications.

In this post I will go through first steps and share the way I catch GraphQL errors in more meaningful way along with setting up InMemoryCache.

Create & Start a project

Open terminal window and then create a folder for our project, cd into it and create projects for our Strapi backend and React frontend:

$ mkdir BestestApp
$ cd BestestApp
$ yarn create strapi-app backend --quickstart
$ npx create-react-app frontend
Enter fullscreen mode Exit fullscreen mode

This will create two folders in our project folder so you have to open two tabs in Terminal in order to start both applications. In one tab cd into BestestApp/backend and start the server:

$ yarn develop
Enter fullscreen mode Exit fullscreen mode

This will start Strapi so you can open this address in your browser: http://localhost:1337/admin. Follow the onscreen instructions and create Admin user. Login and you are in! Welcome to Strapi!
In the second tab navigate to BestestApp/frontend and type

$ yarn start
Enter fullscreen mode Exit fullscreen mode

This will start React application that by default runs on http://localhost:3000/ so go on and open it in another tab.

Install Packages

In order for us to work with Apollo we have to install some packages so let's do that. Open another Terminal tab navigate to BestestApp/frontend and install packages:

$ yarn add @apollo/client apollo-link apollo-link-error graphql
Enter fullscreen mode Exit fullscreen mode

Configure GraphQL and Entry point

Make sure that Strapi server is running and enter the Strapi through the browser using http://localhost:1337/admin. Then go to the Marketplace in the sidebar and make sure that the GraphQL plugin is installed, if it is not, then go ahead and install it. And don't worry if you sometimes get an error here, just refresh the page.

You can now enter your GraphQL endpoints using http://localhost:1337/graphql.

We will now go into editing Index.js in our Frontend so open your favorite IDE or any other editor you use for coding and open BestestApp/frontend/src/Index.js.
We will now implement a GraphQL error check that will show you in the console when something is not right with your request. We will add errorLink creator and a little Apollo magic:
/frontend/src/Index.js

...
import { ApolloProvider, createHttpLink } from '@apollo/client';
import { ApolloClient } from '@apollo/client';
import { onError } from 'apollo-link-error';
import { ApolloLink } from 'apollo-link';

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    console.log('graphQLErrors', graphQLErrors);
  }
  if (networkError) {
    console.log('networkError', networkError);
  }
});

const httpLink = createHttpLink({
  uri: 'http://localhost:1337/graphql',
});

const link = ApolloLink.from([errorLink, httpLink]);

export const client = new ApolloClient({link});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
);
...
Enter fullscreen mode Exit fullscreen mode

We used onError to catch GraphQL and Network errors and show them to console, and we are using the GraphQL endpoint for Strapi http://localhost:1337/graphql. Next we initiate our ApolloClient using a link that uses our errorLink and httpLink. Finally we reference the client in the ApolloProvider wrapping our as the entry to our app.

Configure InMemoryCache

Great thing about Apollo is that it uses in-memory cache which enables our client to respond to queries for the same data with better performance and without unnecessary requests.
We just need to add it to our options config when instantiating new Apollo client with the appropriate data for our types. In this example we have Parts and Products:

...
import { ApolloClient, InMemoryCache } from '@apollo/client';
...
export const client = new ApolloClient({
  link,
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        Part: {
          parts: {
            fields: {
              merge(existing, incoming) {
                return incoming;
              }
            }
          }
        },
        Product: {
          products: {
            fields: {
              merge(existing,incoming) {
                return incoming;
              }
            }
          }
        }
      }
    }
  })
});
...
Enter fullscreen mode Exit fullscreen mode

You can find more on configuring caching here.

Congrats! You are now ready to use GrapQL to read data from the Strapi backend. In some later posts I will go through queries and mutations that are needed for fetching and updating data.

Thanks for reading!

Top comments (0)