React + Prepr CMS

This is the official React + Prepr guide. It’ll explain to you how to quickly install and configure Prepr’s JavaScript SDK, and fetch data from the Prepr CMS using it.

Getting started

In this guide, you’ll learn how to create a React app capable of fetching and using data from the Prepr CMS.

Prerequisites

This guide assumes that you’ve:

  • An active Prepr account.
  • Set-up an environment on Prepr CMS, preferably using the demo content provided by Prepr. This can be done by clicking on Load demo content when setting up the environment.

Creating a new React Project

You can skip this step if you already have an existing React project.

To begin, create a new React project using create-react-app. npx create-react-app prepr-react

Once created, navigate to the project’s root directory using cd prepr-react. Here you can test whether your React app is working fine using npm start. Once started, you should be able to view your app at http://localhost:3000/.

Creating Prepr client

Close the server you started in the above step and add the Prepr’s JavaScript SDK to your app by using the following command:

npm install @preprio/nodejs-sdk

Create a services directory inside the /src directory of your project and in here, create a file named prepr.js using the following commands:

cd src
mkdir services
cd services
touch prepr.js

You’ll use this file to create and configure your Prepr client with the help of createPreprClient provided by the SDK. This client will be used to make API requests to endpoints provided by the Prepr CMS across your React application.

Add the following code to this file.

import { createPreprClient } from '@preprio/nodejs-sdk'

const prepr = createPreprClient({
   token: process.env.REACT_APP_PREPR_ACCESS_TOKEN,  // You can find one in your Prepr environment
   baseUrl: "https://graphql.prepr.io/graphql",
   userId: null, // Optional, used for AB testing implementations
})

export { prepr }

Prepr recommends using environment variables to store your sensitive information like access token. To add environment variables, create a .env to the root directory of your project and add the variable like this:

REACT_APP_PREPR_ACCESS_TOKEN=<your access token>

Fetching data

Now, let’s make use of the Prepr client you created above to fetch some data from the CMS.

If you’re using the same preloaded demo content in your CMS environment as mentioned above in the Prerequisites section, you should have 5 posts in there. Let’s try to fetch their titles. For this you’ll make use of the following GraphQL query:

{
 posts: Posts {
   items {
       title
   }
 }
}

But how do you know if this is the right query? To test your queries, you can make use of Explorer provided under Apollo Studio’s sandbox mode. There you can easily create queries with the help of the documentation pane and check the results in real time. All you’ll need is your unique graphql endpoint, All the necessary information about the endpoint can be found here.

Go to /src/app.js and replace its content with the code below:

import React, { useEffect, useState } from "react";
import { prepr } from "./services/prepr";

function App() {
 const [posts, setPosts] = useState([]);

 async function fetchPosts() {
   const data = await prepr
     .graphqlQuery(
       `{
           posts: Posts {
             items {
                 title
             }
         }
       }`
     )
     .fetch();

   setPosts(data.data.posts.items);
 }

 useEffect(() => {
   fetchPosts();
 }, []);

 useEffect(() => {
   console.log(posts);
 }, [posts]);

 return <div className="App"></div>;
}

export default App;

Here you’re making use of Prepr client to fetch post titles from the CMS. After running the application, when visiting your local React server in the browser, you should be able to see the posts array consisting of post titles in the console panel accessible via inspect mode as shown in the image below:

alt text

Displaying data

Let’s get rid of the second useEffect used to console log the results and actually display the titles in your app.

Open the file src/app.js again and replace its content with the code below:

import React, { useEffect, useState } from "react";
import { prepr } from "./services/prepr";

function App() {
 const [posts, setPosts] = useState([]);

 async function fetchPosts() {
   const data = await prepr
     .graphqlQuery(
       `{
           posts: Posts {
             items {
                 _id
                 title
             }
         }
       }`
     )
     .fetch();

   setPosts(data.data.posts.items);
 }

 useEffect(() => {
   fetchPosts();
 }, []);

 return (
   <div className="App">
     {posts.map((post) => (
       <p key={post._id}>{post.title}</p>
     ))}
   </div>
 );
}

export default App;

Once done, when visiting your local React server in the browser, you should see the following output:

alt text

Learn More

For additional information on using @preprio/nodejs-sdk, check out its documentation.