I came up with the idea to use localStorage as a pretend message bus. It already has events, so it wasn't to hard to implement. At the end is the code for the LocalStorageEventManager but first is how it is used.
index.ts
This is our main component library file. We export two components, the listener Component A and the emitter, Component B. They are as follows...
import React from "react";
import { Retool } from "@tryretool/custom-component-support";
import { LocalStorageEventManager } from "./LocalStorageEventManager";
// Defined a Payload
type ControlMessage = {
action: "fit" | "expandAll" | "collapseAll";
};
// Define Events with Payloads
type Events = {
CONTROL_CLICKED: ControlMessage;
};
// Create an instance with a namespace on localStorage
const LSEM = LocalStorageEventManager<Events>({ namespace: "chartControls" });
/**
* Component A
*/
export const Chart: React.FC = () => {
// Get the `useEffect` hook for an event
// The hook is strongly typed for the listener
const onControlClicked = LSEM.getListenerHook("CONTROL_CLICKED");
// Register the hook and listen for the event
// data will be `ControlMessage`
onControlClicked((data) => {
console.log("control clicked", data);
// data will be { action: "fit" | "expandAll" | "collapseAll" }
});
return ( /* your component */ );
};
/**
* Component B
*/
export const ChartControls: React.FC = () => {
// Get the emitter for an event
const emit = LSEM.getEmitter("CONTROL_CLICKED");
// emit is strongly typed emit(data: ControlMessage) => void
// emit({ action: "nope" }) will produce a typescript error
return (
<div>
<button onClick={() => emit({ action: "fit" })}>Fit To Screen</button>
<button onClick={() => emit({ action: "expandAll" })}>Expand All</button>
<button onClick={() => emit({ action: "collapseAll" })}>Collapse All</button>
</div>
);
};
This solved my problem of having two separate components communicate with each other!
But it looks like we might need to showcase this on our 'Tips and Tricks' page.
For your question on if there is a GitHub repro that is available for the public to submit pull requests and report bugs, I believe there is at tryretool. But let me check with the team on best practices for helping us improve the code base!