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:
Clicking the "Share" button displays a "success" notification and clicking the "Notify" button displays an "error" notification
- Vite App
- Nextjs App
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.
- Vite App
- Nextjs App
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';
loading...
As we want to centralize all notifications, we attach this widget to <AppLayout />
loading...
export const STATE_CART = 'cart';
export const URL_ADD_PRODUCT = '/api/cart/products';
export const URL_CART = '/api/cart';
export const NOTIF_TOPIC_ERROR = 'error';
export const NOTIF_TOPIC_SUCCESS = 'success';
loading...
As we want to centralize all notifications, we attach this widget to <AppLayout />
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
Successnotification when theSharebutton is clicked.
The notification disappears automatically after 5 seconds. - display an
Errornotification when clicking on theNotifybutton.
Clicking on these buttons sends a notification to a specific topic and the <NotificationCenter /> displays them.
- Vite App
- Nextjs App
loading...
loading...
Next step
In the next step, we introduce the services offered by onekijs to handle errors.