Skip to main content

Personalizing on Contentful Data

Once you have installed Uniform to Contentful, the next step is to get the Contentful content into your application and start personalizing it.

Use the contentfulOptimizeListReader function to allow the application to read the Contentful entry data and convert it to a format that Uniform Optimize understands.

Install the Package

Install the library:

npm install @uniformdev/optimize-tracker-contentful

Fetch the Data from Contentful

To show how it works, let us assume we have a Contentful JavaScript SDK query that retrieves a single page entry by matching on the slug field.

export const getPageBySlug = async (preview: boolean, slug: string) => {
const entries = await contentfulClient.getEntries({
content_type: 'page',
'fields.slug': slug,
include: 2,
});

const [first] = entries.items;
return parsePage(first);
};

The page definition content type has a components field, which is an assembly field. One of these components is a Personalized List type, configured with variants, created using the Uniform Contentful app.

The definition for the list component looks like the following:

export interface PersonalizedHeroFields {
/** Personalized Hero Name */
name: string;

/** Hero Options */
unfrmOptP13nList?: Hero[] | undefined;
}

Use the Contentful Data with the Personalize Component

The unfrmOptP13nList field is our list item in this personalized list entry. To read these from the Contentful response and convert them into the format, import the contentfulOptimizeListReader function and pass the field's contents into it. The result can be passed to the variants field of the <Personalize /> component.

import { contentfulOptimizeListReader } from '@uniformdev/optimize-tracker-contentful';
import { Personalize } from '@uniformdev/optimize-tracker-react';

export const PersonalizedHero = ({ fields }) => {
const variations = contentfulOptimizeListReader(fields.unfrmOptP13nList);
return <Personalize variations={variations} />;
};
tip

In the example we used React, but the contentfulOptimizeListReader is framework-agnostic.