React + Prepr CMS

This is the recommended method of using the Prepr SDK with React.js.

Setup

Start by scaffolding a new project or opening up an existing one:

npx create-react-app prepr-react

cd prepr-react

npm i @preprio/nodejs-sdk

Great, we now have a React.js project with the JavaScript SDK for Prepr.

Configuration

We recommend creating lib directory inside the root of your project and containing a file named prepr.js:

mkdir lib

cd lib

touch prepr.js

The prepr.js file will contain the client holding the configuration which will be used for every request made to the Prepr API.

Let's setup our configuration:

// src/prepr.js

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

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

export { prepr }

You can now import the client inside your pages.

Usage

// src/App.js

// Import our configured Prepr client
import { prepr } from './prepr'

import { useEffect, useState } from 'react'

function App() {
  const [collections, setCollections] = useState()

  async function fetchCollections() {
    const data = await prepr
        .graphqlQuery(`{
            posts: BlogPosts {
                items {
                    _id
                    title
                    summary
                    _read_time
                }
            }
        }`)
        .fetch();

    setCollections(data.data.posts.items)
  }

  useEffect(() => {
    fetchCollections()
  }, [])

  return (
    <div className="App">
      {collections.map((collection) => (
        <p>{collection.id}</p>
      ))}
    </div>
  )
}

export default App

For a more detailed usage on the @preprio/nodejs-sdk SDK please read its documentation.