Hooks and Utils
In addition to common components, Theme Rendering engine also injects some common useful hooks and helper functions to the theme build, the hooks and functions can be imported from a global package viz.fdk-core/utils
useGlobalStore
The React hook allows the theme developers to subscribe to a slice of the Redux store. It's a direct extension of React-Redux’s useSelector hook. The useGlobalStore hook is built for direct compatibility with the getters available in fpi.getters.
Example:
import React from 'react';
import { useGlobalStore } from 'fdk-core/utils';
function Home({ fpi }) {
/**
* Get PAGE data from store
*/
const page = useGlobalStore(fpi.getters.PAGE) || {};
/**
* Rendering Logic Here
*/
return (
<p>Home Component</p>
);
}
useClientInfo
The useClientInfo hook provides an easy access to client-specific information such as themeCookie and userAgent throughout your React theme. This enables the theme application to adapt to it's behavior and appearance based on user preferences and client device details.
Purpose
The primary usage of useClientInfo is to:
- Provide global access to
themeCookieanduserAgentdata without passing props through every component level. - Enhance user experience by dynamically adjusting themes and layouts according to the user's setting and client device characteristics.
- Improve code maintainability by centralizing client information retrieval and usage into a single, reusable hook.
- Work in SSR, the hook also works during Server-side rendering (SSR).
Context Values
themeCookie: A value representing the user's preferred theme (e.g light or dark mode), stored in a browser cookie.userAgent: A string that provides information about the client's browser, device and operating system, extracted from the request headers.
How to use useClientInfo
To use the Hook in your React components, follow these steps:
- Import the hook from the utility library where it's defined.
import { useClientInfo } from 'fdk-core/utils';
- Use the hook in your component.
const MyComponent = () => {
const { userAgent, themeCookie } = useClientInfo();
const themeClass = themeCookie === 'dark' ? 'dark-theme' : 'light-theme';
return (
<div className={themeClass}>
<p>Welcome! Your user agent is: {userAgent}</p>
</div>
);
};
Use-cases
- Dynamic Theming: Switch between light and dark-themes based on the
themeCookievalue. - Device-Specific Customization: Adjust UI components or load specific assets based on the
userAgentstring. - Responsive Layouts: Optimize layouts and interactions for different devices using the information provided by the
userAgent.
Conclusion
The useClientInfo hook is a powerful tool for managing client-specific data in a React application. By integrating the hook, developers can create more responsive, user-friendly applications that can adapt to individual's user preference and device capabilities.
getPageSlug
The getPageSlug takes the router object and returns the page slug of the current route, which is used to fetch page specific data from the APIs.
Example:
import { getPageSlug } from 'fdk-core/utils';
export async function pageDataResolver({ fpi, router, themeId }) {
const state = fpi.store.getState();
const pageValue = getPageSlug(router);
const APIs = [];
const currentPageInStore = state?.theme?.page?.value ?? null;
if (pageValue !== currentPageInStore) {
APIs.push(
fpi.theme.fetchPage({
pageValue,
themeId,
}),
)
}
return Promise.all(APIs).catch(console.log);
}
HTMLContent
The HTMLContent component in React takes an HTML string as a content prop and renders it safely in the DOM. Here's a simple example:
import React from "react";
import { HTMLContent } from "fdk-core/components";
function MyComponent() {
return (
<HTMLContent content="<div><h1>Welcome!</h1><p>This is a custom HTML content.</p></div>" />
);
}
export default MyComponent;
useGlobalDispatch
useGlobalDispatch returns the dispatch function of the Redux store. It is a direct extension of
the useDispatch hook of React-Redux, and it is the write counterpart of
useGlobalStore.
Most themes never need it. An FPI method already dispatches its own actions and keeps the store consistent, so call the FPI method first:
await fpi.content.getNavigations(); // Fetches and stores
fpi.custom.setValue("someKey", value); // Writes a custom value
Use useGlobalDispatch only for an action that no FPI method covers:
import React from "react";
import { useGlobalDispatch } from "fdk-core/utils";
function MyComponent() {
const dispatch = useGlobalDispatch();
const onSomething = () => {
dispatch({ type: "custom/someAction", payload: { id: 1 } });
};
return <button onClick={onSomething}>Do something</button>;
}
Do not dispatch during the first render. A dispatch changes the store, and a store change during render can make the client markup differ from the server markup. Dispatch from an event handler or an effect.
emitFPIEvent
emitFPIEvent sends an event to the platform event bus, where analytics extensions and merchant
tags receive it.
emitFPIEvent(eventName, payload, pageType);
| Parameter | Type | Purpose |
|---|---|---|
eventName | string | The name of the event. It is also written into the payload as event_action. |
payload | object | Your event data |
pageType | string | The page the event came from. It is written into the payload as screen_view. |
The helper adds two fields for you:
screen— the screen orientation,portraitorlandscapescreen_view— thepageTypeyou passed
Example:
import { emitFPIEvent } from "fdk-core/utils";
function AddToCartButton({ product, pageType }) {
const onAdd = () => {
emitFPIEvent(
"add_to_cart",
{ product_id: product.uid, quantity: 1 },
pageType
);
};
return <button onClick={onAdd}>Add to cart</button>;
}
Two behaviours to know:
- The helper does nothing on the server. It checks that it runs in the browser first, so it is safe to call from shared code, but an event fired during server rendering is never sent.
- It never throws. A failure is written to the console and the call returns. Do not rely on it to report a problem in your event data.
Read Events for the events the platform already emits.