1. Developer guides

Combine multiple operations

Version: 0.4

In this walkthrough, you combine multiple queries and mutations to build a complex interaction between a Marketplace app and the SitecoreAI Page builder. When the user clicks a button, your app creates a subpage under the currently open page and navigates to it so the user can start working with it straight away.

Consider building such an interaction if your app creates pages, for example, a duplicate of an existing page improved with generative AI.

A Marketplace app creates a subpage under the current one when the user clicks the Improve with AI button.

This walkthrough describes how to:

Before you begin

Query the necessary contexts

Before you can create a subpage, you must query the application context to access the Context ID of your SitecoreAI environment, and the page context to access the details about the currently opened page. Because the user can open a different page any time, you also need to subscribe to page events to keep the page context up to date.

To query the application context and page context:

  1. In the SDK initialization code where you run the useMarketplaceClient hook, in the main function, create state variables for the application context and the page context. If you're using TypeScript, import their types from the client package:

  2. In the Effect Hook where you initialize the Marketplace, query the application context and store the response data in state:

    // Query the application context:
    client.query("application.context")
    .then((res) => {
      console.log("Success retrieving application.context:", res.data);
      setAppContext(res.data);
    })
    .catch((error) => {
      console.error("Error retrieving application.context:", error);
    });
  3. After the application context query, query the page context and store the response in state, then save your changes.

    // Query the page context:
    client.query("pages.context", {
      //  Subscribe to page events:
      subscribe: true,
      onSuccess: (res) => {
        console.log("Success retrieving pages.context:", res);
        setPagesContext(res);
      },
    })
    .catch((error) => {
      console.error("Error retrieving pages.context:", error);
    });

    This script also subscribes to page events.

  4. In the SitecoreAI Page builder, open your web browser's console, refresh the page, then open your Marketplace app.

  5. In the console, find logs for application.context and pages.context and inspect the objects. Because you subscribed to page events, the pages.context object changes as you open different pages in the site tree.

Create a subpage

After querying the necessary contexts, you make a GraphQL query that creates a subpage under the currently opened one.

To create a subpage using GraphQL:

  1. In your code editor, prepare the file you were editing in the previous procedure for a new GraphQLQuery component. To do this, import the component and pass it the necessary data in the return statement, then save your changes. You create the component in the next step.

  2. Create the component, for example, src/components/GraphQLQuery.tsx, then save your changes. If you're using TypeScript, also import ClientSDK from the client package:

    // src/components/GraphQLQuery.tsx
    
    import { ClientSDK } from "@sitecore-marketplace-sdk/client";
    
    export default function GraphQLQuery({
      pagesContext,
      appContext,
      client,
    }: {
      pagesContext: any;
      appContext: any;
      client: ClientSDK | null;
    }) {
      const makeGraphQLQuery = async () => {};
    
      return <button onClick={makeGraphQLQuery}>Create subpage & redirect</button>;
    }
  3. In the makeGraphQLQuery function, retrieve the Context ID from the application context:

    // Get the Sitecore Context ID from the application context:
    const sitecoreContextId = appContext.resourceAccess?.[0]?.context.live;
    // Check if the Sitecore Context ID is available:
    if (!sitecoreContextId) {
      console.error(
        "Sitecore Context ID not found in application context. Make sure your app is configured to use SitecoreAI APIs."
      );
      return;
    }
  4. Below the Context ID script, prepare the GraphQL query string for creating a subpage:

    // GraphQL query to create new page:
    const createNewPageGraphQLQuery = {
      query: `
      mutation {
        createItem(
          input: {
            name: "GenAI Copy of ${pagesContext?.pageInfo?.name}"
            parent: "{${pagesContext?.pageInfo?.id}}"
            templateId: "{${pagesContext?.pageInfo?.template.id}}"
            language: "en"
            # fields: [<...>]
          }
        ) {
          item {
            parent {
              itemId
            }
            itemId
            name
            path
            fields(ownFields: true, excludeStandardFields: true) {
              nodes {
                name
                value
              }
            }
          }
        }
      }
    `,
    };

    This query string is for creating a page with the following details:

    • The name is GenAI copy of plus the name of the currently opened page.

    • The parent is the currently opened page.

    • The templateId is same as that of the currently opened page.

  5. After the GraphQL query string, make the mutation using the query string and the Context ID, then save your changes:

    // Make the GraphQL query:
    const response = await client?.mutate("xmc.authoring.graphql", {
      params: {
        query: {
          sitecoreContextId,
        },
        body: createNewPageGraphQLQuery,
      },
    });

Redirect to the new subpage

After creating the subpage, you retrieve its ID and redirect the user to it.

To open the new subpage:

  1. In your code editor, in the GraphQLQuery component, in the makeGraphQLQuery function, below the mutation function, paste the following code, then save your changes:

    // src/components/GraphQLQuery.tsx
    
    // Retrieve ID of new page:
    const newPageId = response?.data?.data?.createItem?.item?.itemId;
    // Redirect to new page:
    await client?.mutate("pages.context", {
      params: {
        itemId: `{${newPageId}}`,
      },
    });

    This script:

    • Retrieves the ID of the newly created subpage from the GraphQL response.

    • Makes a mutation to open the page with that ID: client?.mutate("pages.context", {<...>})

  2. In the SitecoreAI Page builder, refresh the page, then open your Marketplace app.

  3. In the Marketplace app, click Create subpage & redirect. Your app now creates a subpage and redirects you to it.

Next steps

You've now combined multiple queries to build an app that creates a subpage under the currently opened one and immediately redirects the SitecoreAI user to it.

Next, you can:

  • Explore the Authoring and Management GraphQL API to make more complex queries and mutations. For example, to update the contents of the new subpage.

  • Develop the functionality of your app that generates new page content based on the existing one.

If you have suggestions for improving this article, let us know!