Search⌘ K
AI Features

React Domain Events

Explore how to handle domain events in a React application using MicroEventBus. Understand subscribing to user login and broadcasting cart item events, updating component states with TypeScript, and preparing your app as a micro front-end for scalable architecture.

What are we dealing with?

There are two Domain Events that our React front-end needs to deal with:

  • The first is an incoming event where we are notified that a user has logged in to the application. This event provides us with the username of the logged-in user, which we will need when we broadcast a Domain Event.

  • The second Domain Event is one that we will need to broadcast when a user clicks the “Add to Cart” button in the DetailView component. This event will include the username, the productId that was selected, as well as the amount of switches the user has entered.

In order to test that our React application can consume and produce these Domain Events in a test environment, we will need to copy the MicroEventBus.js file from our micro-event-bus/dist directory into the product-list/public directory. We will also need to update our product-list/public/index.html file as follows:

HTML
<html lang="en">
<head>
<!-- Existing Tags -->
<script src="/MicroEventBus.js"></script>
</head>
<body>
<noscript> You need to enable JavaScript to run this app. </noscript>
<div id="root"></div>
<script>
testBroadcast();
function testBroadcast() {
window.microEventBus
.on("add-user-cart-item")
.subscribe(function (event) {
console.log(`IDX : add-user-cart-item received : `);
console.log(`IDX : ${JSON.stringify(event, null, 4)}`);
});
}
function sendMessage() {
window.microEventBus.broadcast("user-logged-in", "test_user_1");
}
</script>
<button onclick="sendMessage()">Send user event</button>
</body>
</html>

  • We have updated our index.html file and included the MicroEventBus.js file as a <script> resource on line 4 of our code. We have also added a <script> section to the <body> tag of this file in a similar manner to the test code that we used in the micro-event-bus/dist/index.html file.

  • This test code on lines 12–19, registers a listener to the 'add-user-cart-item' domain event, which will log the values found as properties of the event to the console.

  • We have also added a ...