Creating Frontastic component with a data source

👍

Prerequisites

As mentioned in the creating a configurable Frontastic component article, you can provide a schema that makes the Frontastic studioFrontastic studio - The interface you use to manage, build, and edit all areas of your project and commerce sites. Previously known as `backstage`. render a configuration interface for your Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. whenever it's used on a page. The resulting configuration is delivered to the mounted React component of the Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. as the prop data.

You can create a Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. to utilize data from your API provider. To do this you need to set this up within your index.tsx component file and within the schema.json file. To require a data source of a certain type you first need to upload a corresponding data source schema. See the developing a data source extension article for more information.

In this example, we're using a data source with the below schema and the extension configuration to implement the data source code:

{
  "customDataSourceType": "example/star-wars-character-search",
  "name": "Star wars character search",
  "category": "Content",
  "icon": "source",
  "schema": []
}
'data-sources': {
    'example/star-wars-character-search': async (
      config: DataSourceConfiguration,
      context: DataSourceContext,
    ): Promise<DataSourceResult> => {
      const pageSize = context.request.query.pageSize || 10;
      const after = context.request.query.cursor || null;
      return await axios
        .post('https://swapi-graphql.netlify.app/.netlify/functions/index', {
          query: `{
            allPeople(first: ${pageSize}, after: ${JSON.stringify(after)}) {
              totalCount
              pageInfo {
                hasNextPage
                endCursor
              }
              people {
                id
                name
                species {
                  name
                }
              }
            }
          }`,
        })
        .then(
          (response): DataSourceResult => {
            return {
              dataSourcePayload: response.data?.data?.allPeople || {},
            } as DataSourceResult;
          },
        )
        .catch((reason) => {
          return {
            dataSourcePayload: {
              ok: false,
              error: reason.toString(),
            },
          } as DataSourceResult;
        });
    },
  },

To bring the data sourcedata source - The data provided from an API to display products, content, or anything from an integration or extension. A data source filter is created and can be selected for a Frontastic component that will display the data source filter on your commerce site. into a Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code., it needs to have a field type of stream and it needs to have a streamType within the schema.json file.

Schema type and data sources

The schema array of the Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. schema allows you to group configuration fields into logical (and in the Frontastic studioFrontastic studio - The interface you use to manage, build, and edit all areas of your project and commerce sites. Previously known as `backstage`. visual) sections. Each section can contain any number of configuration fields:

{
  "tasticType": "example/star-wars/character-search",
  "name": "Star Wars character search",
  "category": "Content",
  "icon": "perm_identity",  
  "description": "A Frontastic component with a data source example",
  "schema": [
    {
      "name": "Data source",
      "fields": [
        {
          "label": "Characters",
          "field": "data",
          "type": "stream",
          "streamType": "example/star-wars-character-search",
          "required": true
        }
      ]
    }
  ]
}

In this example, the schema of the StarWarsCharacterSearchTastic received a section Data source which contains exactly 1 configuration field: data. The field is of type stream, and the streamType must be something that's been uploaded to the Frontastic studioFrontastic studio - The interface you use to manage, build, and edit all areas of your project and commerce sites. Previously known as `backstage`. (see the developing a data source extension article for more information. We're using our example/star-wars-character-search data source for this example.

As we've set required to true, when we add the Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. to the page it's shown as red with a warning:

Uploading this schema to the Frontastic studioFrontastic studio - The interface you use to manage, build, and edit all areas of your project and commerce sites. Previously known as `backstage`. and editing it on a page results in the following settings form:

We can now click + Add data source filter to bring the data into the component. See the using the data source filter editor article for how to use the filter editor.

Once you've configured your schema.json for your Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. with a streamType, you can then automatically access the data in your index.tsx file in the corresponding field name. You can then deal with that data as you wish, for example, display the data, send the information to another server, and so on.

The API hubAPI hub - The API hub combines our code, your code, and APIs to create the backend of a commerce site. Any backend development or extensions are done here. Known as `Catwalk` in code. then does all the magic to display products to your customers as they navigate your site.

Find out more about schemas and a complete list of field types and their possibilities in Frontastic schemas.

Frontastic component input in code

In the React entry point of your Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code., Frontastic automatically provides you with the prop data which contains the entire configuration from the Frontastic studioFrontastic studio - The interface you use to manage, build, and edit all areas of your project and commerce sites. Previously known as `backstage`..

import React from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';

const StarWarsCharacterSearchTastic = ({ data }) => {
  const { totalCount, pageInfo, people } = data.data.dataSource;
  const router = useRouter();

  const { slug, ...queryWithoutSlug } = router.query;

  return (
    <div>
      <h1 className="text-2xl mt-8 font-sans">Star Wars Characters</h1>
      <p className="mt-2">{totalCount} total characters found</p>
      {people.map((character) => (
        <div key={character.id}>
          <h2 className="text-lg mt-6 font-sans">{character.name}</h2>
          {character.species !== null && <p className="mt-2">Species: {character.species.name}</p>}
        </div>
      ))}
      {pageInfo.hasNextPage && (
        <div className="mt-6">
          <Link
            href={{
              pathname: router.asPath.split('?')[0],
              query: {
                ...queryWithoutSlug,
                cursor: pageInfo.endCursor,
              },
            }}
          >
            <a className="bg-primary-500 px-4 py-2 text-white">Next Page</a>
          </Link>
        </div>
      )}
    </div>
  );
};

export default StarWarsCharacterSearchTastic;

The index.tsx defines a type for the data prop derived from the Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. schema. In the code, the provided data can then directly be accessed. It's the data.dataSource that takes the configuration from the studio.

❗️

It's important to note that the structuring in sections in the schema field in the Frontastic componentFrontastic component - A customizable building block that's used together with other components to create a commerce site. Known as `tastic` for short in code. schema is only for visualization purposes. The field identifiers in different sections are all global. That means you can freely regroup fields into sections, but also that field identifiers must be unique across all sections!

🚧

You can have multiple components on the same page using the same data source. But, data sources don't communicate with each other (unless you configure this yourself), so you could see the same thing in both components.


Did this page help you?