This example show how to integrate the SDK with REACT UI components. In the past, it was not possible to synchronize React's life cycle with the global object(window), so we had to use Hack to do so.
like below:
const Provider = ({ children }: { children: any }) => {
const [data, setData] = useState<ContextState>({
project: null,
user: null,
workspaces: [],
lang: i18n.language.substring(0, 2),
design: null,
});
const setProject = (project: Project) => {
setData((prev) => ({ ...prev, project }));
};
const setDesign = (newDesign: Partial<Design>) => {
setData((prev) => ({ ...prev, design: { ...prev.design, ...newDesign } }));
};
const logout = () => {
setData((prev) => ({ ...prev, user: null }));
};
window.sdk.setProject = setProject;
window.sdk.setDesign = setDesign;
window.sdk.logout = logout;
...
We make a React Provider component that serve as a bridge between the SDK and the React components. The problem is that we have to use the global object(window) to expose the functions to the SDK, and this is NOT a good practice.
Now, we can use the new SDK to do the same thing, but in a better way using useSyncExternalStore
You can make a global SDK with React UI components easily and cleanly by using this method.
function App() {
const data = useSyncExternalStore(
mySDKStore.subscribe,
mySDKStore.getSnapshot,
);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>{data.label}</p>
<button
onClick={() => {
window.setLabel('new Label');
}}
>
Button
</button>
</header>
</div>
);
}
And you can check the implementation in src/external.ts
let data = { label: 'Edit src/App.tsx and save to reload.' };
let listeners: Array<() => void> = [];
export const mySDKStore = {
setLabel(newLabel: string) {
data = { label: newLabel };
emitChange();
},
subscribe(listener: () => void) {
listeners = [...listeners, listener];
return () => {
listeners = listeners.filter((l) => l !== listener);
};
},
getSnapshot() {
return data;
},
};
function emitChange() {
for (let listener of listeners) {
console.log(1);
listener();
}
}
window.data = data;
window.setLabel = mySDKStore.setLabel;
We can use global scope object as a hook into the components. This allows us to use the SDK in a more natural way. It's just like a normal React component.
- Install dependencies
pnpm install
- Run React Project
pnpm run start
It will start the application in http://localhost:3000
- You can click the button in the webpage or use the console to change the label.
// in your browser console
window.setLabel('new label');