Sitecore Marketplace - XM Cloud SDK
In my previous post I explained how to get started with a new, Vite based, Sitecore Marketplace App.
In this post I will show how to install the XM Cloud SDK on top of that.
Installing the SDK
First, install the XM Cloud SDK by running the following command
npm install @sitecore-marketplace-sdk/xmc
After installing the package, we need to update the Client SDK initialization to insert the xmc module.
Do this by adding the ‘xmc’ module in the ClientSDK.init.
If you have followed the quick start guide, you will find this in /src/components/UserInfo.tsx near line 24.
Make sure to add an import of XMC to the top of the file.
import { XMC } from "@sitecore-marketplace-sdk/xmc";
...
const client = await ClientSDK.init({
origin,
target: window.parent,
// Extend Client SDK with the `xmc` package:
modules: [XMC],
});
Using the XM Cloud APIs
We will now add a button to our application to retrieve a list of XM Cloud site collections that exist within the context tenant.
Make the following changes to /src/components/UserInfo.tsx
Add a new state container near line 15.
const [xmcCollections, setXmcCollections] = useState({});
Add a function which retrieves a list of collections from the XM Cloud API. Add this underneath the fetchUser method.
Replace <YOUR_PREVIEW_CONTEXT_ID> with the Preview context ID of your XM Cloud environment.
// Example of XMC request:
const fetchXMCCollections = async () => {
const collections = await clientRef.current!.query(
"xmc.xmapp.listCollections",
{
params: {
query: {
sitecoreContextId: "<YOUR_PREVIEW_CONTEXT_ID>",
},
},
}
);
console.log(collections);
if (collections?.data) setXmcCollections(collections.data);
};
Add a button to the response which triggers the new fetchXMCCollections method and displays the results.
Replace the return (…) near line 73 with the following code.
return (
<>
<div>
<button onClick={fetchUser}>Get user details</button>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
<div>
<button onClick={fetchXMCCollections}>Fetch XMC collections</button>
<pre>{JSON.stringify(xmcCollections, null, 2)}</pre>
</div>
</>
);
Now run your application and test it in the browser. Clicking the button should display a list of site collections that exist in your XM Cloud environment.