Setup Contentful and GraphQL Apollo Client in React Native
In this post, I’m going to set up Contentful (a headless CMS platform) in React Native App using GraphQL Apollo Client. I’ll show this setup in the NX workspace as well as the Expo platform.
Overview
Prerequisite
I am assuming the reader has a basic understanding of the react-native framework. A basic understanding of GraphQL, Apollo Client, and Contentful will be good, but I will give a short introduction of them and also will explain the reason why I choose them. I’ll use a free account of contentful in this post.
Technologies
GraphQL
Similar to React, React Native, GraphQL also was developed by Facebook (now known by Meta) internally and published in 2015 for the public as an open-source project. It was developed to overcome some of the drawbacks of Rest APIs.
GraphQL is a query language used for APIs. It is preferred where data is changing very frequently to optimize API calls. It fetches only the required data. On the other hand, Rest APIs fetch complete data for each call. With graphQL, it is very easy to customize fields for each API call. [To know more about it, please go through graphQL’s official documentation.]
Apollo Client
It is a fully-featured state management library that manages data using GraphQL. This library makes it easy and handles optimization with it to fetch, cache, and update data with little configuration. [To know more about it, please go through apollo graphQL’s official documentation.]
Contentful
Headless content management systems (CMS) are trending these days because here we can manage content without having our own backend system. These headless CMS provide support for each platform which makes them more popular to use for business.
Contentful is one such headless CMS platform where we can manage the content of our own website or app without having any technical knowledge. [To know more about contentful services, please visit their website. Note: contentful services are paid and I’m not associated with any of their services. I’m using a free account for learning purposes only.]
Implementation
I’ll do this setup for a react native app in both expo as well nx workspace.
Please find the final react native app from here.
- For Expo click here
- For NX workspace click here
Setup basic React Native App
- In expo platform (here)
expo init quick-news-appcd quick-news-appnpm installexpo start
- In NX workspace (here)
npx create-nx-workspace quick-news-repo
This command will show a list of apps you want to create in this workspace. Here choose react-native.
Now, type the application name you want. For me it’s quicknews
Want to use Nx cloud? go for default No
cd quick-news-repo
Now, run react-native app quicknews
- for ios
npx nx run-ios quicknews
- for android
npx nx run-android quicknews
The basic setup for react native app is done. Now, I’ll set up contentful.
Setup Contentful space
- Login to contentful for a free account
On successful login, you will get to contentful space
- Add content type Posts
- Add fields to this content type
Now, go to the Content tab from the header
- Add entry / Add posts
- Add posts content and publish it
Now, go to Info section in right panel and copy ENTRY ID
This is the unique id for this entry in this space, I’ll use this entry id later to fetch the content of this particular post.
Now, click on Settings in the header and select API Keys
- Select content delivery/preview tokens and add API key
Fill name for API token copy Space Id, Content Delivery API — access token
Please keep space id and content delivery api access token (CDA Access Token) safely and do not share these with anyone. Note: I’ll delete this token before publishing this post.
Write graphQL query on Contentful GraphiQL server
https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}/explore?access_token={CDA_ACCESS_TOKEN}
Here, SPACE_ID and CDA_ACCESS_TOKEN are the same that I saved in the last step. After updating, variables with their value URL will look like this
https://graphql.contentful.com/content/v1/spaces/di6fj96h9cer/explore?access_token=6a76ZutNtjA8_v0IshR_eIWVnSRYiV-O-_Ikcwe8obs
Open this URL in a new tab, we will get the GraphiQL dashboard, where we can write queries to fetch data from contentful space.
- GraphQL query to fetch single entity
- GraphQL query to fetch collections of entities of same content type
Now, all set up. Let's go to react native app and fetch this data from there.
Setup Contentful GraphQL APIs using Apollo Client
In this section, I’ll show you the actual implementation of contentful graphQL APIs.
- Install required NPM packages
npm install @apollo/client graphql
Async storage as mobile local storage to persist cache
npm install @react-native-async-storage/async-storagenpm install apollo3-cache-persist
Now, I’ll start writing code in react native app.
Note: NX workspace by default uses TypeScript while Expo uses JavaScript.
Those who are working in NX workspace need to save file name as tsx extension while in expo save file as js extension.
- Screen Loader
Create a loader component which we’ll use to show while fetching data from APIs.
- Loader.tsx/.js
- Post component
This component will show each data of a single post entity.
- Post.tsx/.js
- Posts screen
In this screen, we’ll call graphQL query and will get data for the collection of posts entity.
- Posts.tsx/.js
import { gql, useQuery } from '@apollo/client';
- GraphQL query for a single entity
- GraphQL query for collections of posts entity
- Call query using useQuery function, this function returns data, loading status
const { data, loading } = useQuery(QUERY_COLLECTION);
Finally, we fetched the data from the graphQL query.
Now, let's see the complete posts.tsx/.js file
- Create ApolloClient
Now, go to App.tsx/.js file to create a client.
Here, we’ll create an ApolloClient using contentful credentials (Space Id and Content Delivery Api — Access token) that I asked you to save in previous steps.
Note: At this stage, please use your own space id and Content Delivery Api Access token
- App.tsx/.js
Now, wrap all components of App in ApolloProvider
<ApolloProvider client={client}> ...</ApolloProvider>
- Complete App.tsx/.js file
All setup is done now. React Native App is ready to run with contentful content. But, at the time of writing this post, the default configuration of metro bundler does not include file type “cjs”. If in the future it includes, then this step will not be required.
- Extend metro default configuration
Here, we’ll extend the default configuration of metro bundler to support file type “cjs”.
- For NX workspace
In the root of the workspace, metro.config.js will already be present.
Open metro.config.js and add source extension “cjs” in the resolver section.
All done for the NX workspace. Now, run the react-native app.
- For Expo platform
In expo react native app, metro.config.js will not be there in the default app setup.
I have to create it manually at the root of the project.
- Create a file metro.config.js
All done for expo react native app too.
Final screenshot of the ios app simulator
Final screenshot of the android emulator
Wow! we did it. Happy Learning!!!
As this is my first post, any kind of suggestions or feedback is most welcome.