Getting Started

Last updated 5 minutes ago

Connect React app with Campaign Service GraphQL API and use Apollo Client

This is a guide on getting started with React and Apollo Client and how to connect it with CoreMedia’s Campaign Service GraphQL API.

Prerequisites

To follow this tutorial, you need:

  • Node.js version 16

  • pnpm version 7

  • A CoreMedia Content Cloud account with Campaign Service

Create a new React application

The first thing is to bootstrap a new React application. Run the following commands in your terminal:

pnpm create vite campaign-app --template react-ts
cd campaign-app
pnpm install
pnpm run dev

pnpm create vite campaign-app --template react-ts creates a new React project based on Vite and TypeScript.

Open http://localhost:5173/ in your browser and find the default "Vite + React" screen.

Vite + React Startscreen

Your application is now ready to be developed.

Create a campaign

The next step is to create a campaign.

Login to your CoreMedia Content Cloud account. Open CoreMedia Studio and click Campaigns in the menu. Click the + button and create a new campaign (see Create a Link).

Fetch Campaigns using GraphQL

In this guide, you will fetch the data and display them in the created React app.

The main advantage of GraphQL is that developers can request and define the data included in the response. Additionally, GraphQL endpoints are self-documenting, and there is no need to install additional tooling or SDKs.

To find out what data is available via the GraphQL endpoint, we’re using GraphiQL. It is an in-browser tool that allows you to write GraphQL queries and to explore the available data and schema.

CoreMedia Campaign Service GraphQL API needs authentication via an Authorization HTTP header. You receive the token together with your login information.

Open the following URL https://api.campaigns.coremedia.io/ and add your authentication token in the bottom left menu "Headers".

{
  "Authorization": "<your-token>"
}

You can find the GraphQL schema documentation directly in GraphiQL, and you can write GraphQL queries with handy auto-completion.

First you start with a simple query to fetch all channelTypes, that are supported by CoreMedia Campaign Service.

query getChannelTypes {
  channelTypes
}
The Result of the Query
{
  "data": {
    "channelTypes": [
      "category-page",
      "product-page",
      "content-page"
    ]
  }
}

channelTypes are used to query content for a specific page.

We assume that you created a campaign with content linked to the hero slot, and you know the ID of your site. So in the next step you will query for the campaign and the according content.

query CampaignContent(
  $site: String!
  $channelType: String!
  $slotsNames: [String!]
  $refinements: [String!]
) {
  campaignContent(site: $site, channelType: $channelType, refinements: $refinements) {
    slots(names: $slotsNames) {
      name
      assignment {
        campaign {
          id
        }
        items {
          id
        }
      }
    }
  }
}

In this query you need to submit the variables site and channelType. The variables slotNames and refinements are optional. Add them in the bottom left in the interface as variables.

{
  "site": "<your-site-id>",
  "channelType": "category-page",
  "slotsNames": "hero",
  "refinements": [
    "women",
    "dresses"
  ]
}

With this query you can move on and start fetching data from within the created React application.

Refer the Campaign GraphQL API Documentation for further details.

Preview Campaigns using GraphQL

In this guide you will learn, how to use the Preview API of the Campaign Service to preview upcoming campaigns.

Preview the campaign content of a well-known campaign:

query CampaignPreview($campaignId: ID!,  $channelType: String!, $refinements: [String!]) {
  campaignPreview(campaignId: $campaignId, channelType: $channelType, refinements: $refinements) {
    slots(names: $slotsNames) {
      id
      name
      assignment {
        id
        campaign {
          id
        }
        items {
          id
        }
      }
    }
  }
}

In this query you need to submit the variables campaignId, channelType, and slotname. Add them in the bottom left in the interface as variables.

{
  "$campaignId": "<your-site-id>",
  "channelType": "category-page",
  "slotsNames": "hero"
}

Preview Campaigns that are paused or still in draft

Use #previewCampaignContent to display campaign managed content, even if the campain is still in status draft or paused. The parameters and the result type of #previewCampaignContent are the same as for #campaignContent.

query CampaignContent(
  $site: String!
  $channelType: String!
  $slotsNames: [String!]
  $refinements: [String!]
) {
  previewCampaignContent(site: $site, channelType: $channelType, refinements: $refinements) {
    slots(names: $slotsNames) {
      name
      assignment {
        campaign {
          id
        }
        items {
          id
        }
      }
    }
  }
}

In this query you need to submit the variables site and channelType. Add them in the bottom left in the interface as variables.

{
  "site": "<your-site-id>",
  "channelType": "category-page",
  "slotsNames": "hero",
  "refinements": [
    "women",
    "dresses"
  ]
}

Add Apollo Client to the React App

Apollo Client is a state management library that enables you to manage data with GraphQL in React. For a detailed guide check the official documentation.

Run the following command to install both of these packages:

pnpm add @apollo/client graphql

Open your src/main.tsx and change it to the following code to connect your client to React.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import {ApolloClient, ApolloProvider, createHttpLink, InMemoryCache} from "@apollo/client";
import {setContext} from "@apollo/client/link/context";

const httpLink = createHttpLink({
  uri: 'https://api.campaigns.coremedia.io/',
});

const authLink = setContext((_, {headers}) => {
  return {
    headers: {
      ...headers,
      authorization: "<your-auth-token>",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App/>
    </ApolloProvider>
  </React.StrictMode>
)

Now edit your src\App.tsx to fetch data with the React hook useQuery and the query your used before:

import './App.css'
import {useQuery, gql} from '@apollo/client';

function App() {
  const site = "<your-site-id>";
  const channelType = "category-page";
  const slotName = "hero";
  const getCampaignContentQuery = gql`
    query CampaignContent(
      $site: String!
      $channelType: String!
      $slotsNames: [String!]
    ) {
      campaignContent(site: $site, channelType: $channelType) {
        slots(names: $slotsNames) {
          name
          assignment {
            items {
              id
            }
          }
        }
      }
    }
  `;
  const {loading, error, data} = useQuery(getCampaignContentQuery, {
    variables: {
      "site": site,
      "channelType": channelType,
      "slotsNames": slotName
    }
  });
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return (
    <div className="App">
      <h1>
        Campaign Content id for slot <em>"{slotName}"</em><br/>
        with channelType <em>"{channelType}"</em>:<br/>
        <b>{data?.campaignContent?.slots[0]?.assignment?.items[0]?.id}</b>
      </h1>
    </div>
  )
}

export default App

Your browser should automatically reload and show a page like this:

React app with campaign content id

Summary

In this tutorial, you learned how to fetch content IDs for given slot and channel type from within a new React application using GraphQL via Apollo client.

In the next guide you will learn how to get the content data for the given ID from the CoreMedia Content Cloud Headless Server. It will also show you, how to get the content data and the campaign data stitched together in one request.

Copyright © 2023 CoreMedia GmbH, CoreMedia Corporation. All Rights Reserved.