Skip to main content

Centralizing notifications

This step consists in sending all notifications to a "notification center" in charge of displaying them.

Final result

The result of this step is as follows:

New in this step

Clicking the "Share" button displays a "success" notification and clicking the "Notify" button displays an "error" notification

note

onekijs provides two hooks to centralize notifications:

  • useNotificationService returns a service to send notifications on a topic (error topic, success topic, ...)
  • useNotifications returns notifications for a specific topic. Each time a notification is added or removed from the topic, the component is refreshed.

A notification is a javascript object containing at least these fields:

const notification = {
// the topic used for sending the notification (e.g: error)
topic: 'error',
// Time to leave of the notification in milliseconds. Default value=0 (means no expiration)
ttl: 0,
// you can put whatever you want in the notification. We recommend to create a payload object
// containing a message property
payload: {
message: "An error occured while adding the product"
}
...
}

Notification center

onekijs provides a service to send notifications, but not a widget to display them.
First, let's create the "Notification Center" widget to display them. If the topic is success, the notification appears in green and if it's error, the notification appears in red.

src/modules/core/libs/constants.ts
export const STATE_CART = 'cart';
export const URL_ADD_PRODUCT = '/cart/products';
export const URL_CART = '/cart';
export const NOTIF_TOPIC_ERROR = 'error';
export const NOTIF_TOPIC_SUCCESS = 'success';

getting-started/cra/step06-notification/src/modules/core/components/NotificationCenter.tsx
loading...

As we want to centralize all notifications, we attach this widget to <AppLayout />

getting-started/cra/step06-notification/src/modules/core/layouts/AppLayout.tsx
loading...

Sending the notifications

So far, the page listing the products uses the built-in function window.alert() to display a notification.
We want to:

  • display a Success notification when the Share button is clicked.
    The notification disappears automatically after 5 seconds.
  • display an Error notification when clicking on the Notify button.

Clicking on these buttons sends a notification to a specific topic and the <NotificationCenter /> displays them.

getting-started/cra//step06-notification/src/pages/products/index.tsx
loading...

Next step

In the next step, we introduce the services offered by onekijs to handle errors.