Skip to content

Instantly share code, notes, and snippets.

@Vishalsh
Last active February 6, 2025 22:58
Show Gist options
  • Save Vishalsh/a04a71cfe114aa28e4253e83142084dd to your computer and use it in GitHub Desktop.
Save Vishalsh/a04a71cfe114aa28e4253e83142084dd to your computer and use it in GitHub Desktop.
Cross Micro Frontend communication using browser custom events
// Catalog MFE
const Catalog = () => {
// fetch initial count first
const [productsInCartCount, setProductsInCartCount] = useState(initialCount || 0);
const addToCart = () => {
const addToCartEvent = new CustomEvent('ADD_TO_CART', { detail: { count: productsInCartCount + 1 } });
window.dispatchEvent(addToCartEvent);
}
return (
<Product onAddToCart={addToCart} />
)
}
// Cart MFE
const Cart = () => {
// fetch initial count first
const [productsInCartCount, setProductsInCartCount] = useState(initialCount || 0);
useEffect(() => {
const listener = ({ detail }) => {
setProductsInCartCount(detail.count);
}
window.addEventListener('ADD_TO_CART', listener)
return () => {
event.unsubscribe('ADD_TO_CART', listener);
}
}, []);
return (
<NumberOfProductsAdded count={productsInCartCount} />
)
};
@Eghizio
Copy link

Eghizio commented Feb 6, 2025

I believe there is a typo in useEffect cleanup function.

https://gist.github.com/Vishalsh/a04a71cfe114aa28e4253e83142084dd#file-crossmfecommunicationusingcustomevents-js-L29

Instead of:

return () => {
      event.unsubscribe('ADD_TO_CART', listener);
}

Should be:

return () => {
      window.removeEventListener('ADD_TO_CART', listener);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment