This is what my hook looks like at present.
import { useCallback, useEffect, useRef, useState } from "react";
import { createEmbeddingContext } from "amazon-quicksight-embedding-sdk";
import type {
DashboardExperience,
FrameOptions,
EmbeddingContext,
} from "amazon-quicksight-embedding-sdk/dist";
export const useQuickSightDashboard = (iframeCustomStyle: string) => {
const quickSightURL = MYWORKINGURL;
const dashboardRef = useRef<HTMLDivElement>(null);
const [embeddedDashboard, setEmbeddedDashboard] =
useState<DashboardExperience | null>(null);
const [dashboardUrl, setDashboardUrl] = useState<string | null>(null);
const [embeddingContext, setEmbeddingContext] =
useState<EmbeddingContext | null>(null);
useEffect(() => {
const timeout = setTimeout(() => {
fetch(quickSightURL)
.then((response) => response.json())
.then((response) => {
setDashboardUrl(response.EmbedUrl);
});
}, 2000);
return () => clearTimeout(timeout);
}, []);
const createContext = async () => {
const context = await createEmbeddingContext({
onChange: (changeEvent, metadata) => {
console.log("Context received a change", changeEvent, metadata);
},
});
setEmbeddingContext(context);
};
const embedDashboard = useCallback(async () => {
if (dashboardUrl && dashboardRef.current) {
const options: FrameOptions = {
resizeHeightOnSizeChangedEvent: true,
url: dashboardUrl,
container: dashboardRef.current,
withIframePlaceholder: true,
className: iframeCustomStyle,
};
const contentOptions = {
onMessage: async (messageEvent: {
eventName: string;
message: {
title: string;
errorCode: string;
changedParameters: object;
};
}) => {
switch (messageEvent.eventName) {
case "SIZE_CHANGED": {
console.log(
"Size changed. New dimensions:",
messageEvent.message,
);
break;
}
case "CONTENT_LOADED": {
console.log("Content Loaded:", messageEvent.message);
try {
const sheets = await newEmbeddedDashboard.getSheets();
const { SheetId } = sheets[0];
const visuals =
await newEmbeddedDashboard.getSheetVisuals(SheetId);
const { VisualId } = visuals[2];
const newAction = await newEmbeddedDashboard.addVisualActions(
SheetId,
VisualId,
[
{
Name: "VizAction",
CustomActionId: "customvizaction",
Status: "ENABLED",
Trigger: "DATA_POINT_CLICK",
ActionOperations: [
{
CallbackOperation: {
EmbeddingMessage: {},
},
},
],
},
],
);
console.log("newAction", newAction);
} catch (error) {
console.log(error);
}
setEmbeddedDashboard(newEmbeddedDashboard);
break;
}
case "CALLBACK_OPERATION_INVOKED":
console.log("Callback operation invoked:", messageEvent.message);
break;
default:
console.warn(`Unhandled event: ${messageEvent.eventName}`);
break;
}
},
};
const newEmbeddedDashboard = await embeddingContext.embedDashboard(
options,
contentOptions,
);
}
}, [dashboardUrl, embeddingContext, iframeCustomStyle]);
useEffect(() => {
if (dashboardUrl) {
createContext();
}
}, [dashboardUrl]);
useEffect(() => {
if (embeddingContext) {
embedDashboard();
}
}, [embedDashboard, embeddingContext]);
return { dashboardRef, embeddedDashboard };
};```