Skip to content

Instantly share code, notes, and snippets.

@essejmclean
Last active October 25, 2023 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save essejmclean/95624270fe321cf5ed2d340324755420 to your computer and use it in GitHub Desktop.
Save essejmclean/95624270fe321cf5ed2d340324755420 to your computer and use it in GitHub Desktop.
Load Marker.io Widget in React
"use client";
import markerSDK, {
type MarkerProjectWidgetParams,
type MarkerSdk,
} from "@marker.io/browser";
import { useEffect, useMemo, useState } from "react";
// Import environment variables.
const MARKERIO_PROJECT_ID: string | undefined = process.env.MARKERIO_PROJECT_ID // <- CHANGE THIS IN YOUR CODE
/**
* Custom hook for initializing and managing a Marker.io widget.
*
* @param params - Configuration parameters for the Marker.io widget.
* @returns The initialized MarkerSdk instance or undefined.
*/
const useMarkerIo = (
params?: MarkerProjectWidgetParams
): MarkerSdk | undefined => {
// Local state to keep track of the Marker.io instance.
const [markerIo, setMarkerIo] = useState<MarkerSdk | undefined>(undefined);
// Load the Marker.io widget when the component mounts.
useEffect(() => {
// If project ID is missing, log a warning and exit the function.
if (!params || !params.project) {
console.warn(
`Marker.io project ID not found. Skipping Marker.io widget.`
);
return;
}
/**
* Asynchronously load and initialize the Marker.io widget.
*/
const loadWidget = async () => {
try {
// Try loading the widget and update the state if successful.
const marker = await markerSDK.loadWidget(params);
setMarkerIo(marker);
} catch (error) {
// Log any errors encountered during loading.
console.error(error);
}
};
// Execute the loadWidget function.
loadWidget();
}, [params]); // Effect dependencies: re-run if params change.
// Return the Marker.io instance.
return markerIo;
};
/**
* React component to initialize and embed the Marker.io widget.
* Utilizes the `useMarkerIo` custom hook for the actual initialization.
*/
export function MarkerIoWidget() {
// Memoize params to avoid unnecessary re-renders and re-initializations.
const params = useMemo(() => {
return MARKERIO_PROJECT_ID ? { project: MARKERIO_PROJECT_ID } : undefined;
}, []); // No dependencies: useMemo will only compute the value once and cache it.
// Invoke the custom hook.
useMarkerIo(params);
// Return null to avoid rendering anything in the DOM.
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment