The useMessages
hook provides a way to manage application messages (notifications, alerts, etc.) in a React application. It allows you to add, remove, and clear messages throughout your application.
Import
import { useMessages } from '@ollie-shop/sdk';
Usage
const { messages, addMessage, removeMessage, clearAll } = useMessages();
// Add a new message
addMessage({
type: 'success',
content: 'Order completed successfully!'
});
// Remove a specific message
removeMessage(messageId);
// Clear all messages
clearAll();
Return Value
Returns an object with:
messages: Message[]
- Array of all current message objects
addMessage: (message: Omit<Message, "id">) => void
- Function to add a new message
removeMessage: (messageId: string) => void
- Function to remove a message by its ID
clearAll: () => void
- Function to clear all messages
Message Object
Each message in the messages
array has the following structure:
{
id: string; // Automatically generated unique ID
type: enum; // Type of message (e.g., 'success', 'error', 'info', 'warning')
content: string; // The actual message content
title?: string; // Optional title for the message
}
Message is described by the following structure:
Property | Type | Description |
---|
id | string | A unique identifier for the message (automatically generated) |
type | enum | The type of message success | warning | error |
content | string | The main text content of the message |
title | string | Optional title for the message |
Example
The example below shows two different messages, a success
and an error
Desktop | Mobile |
---|
 |  |
To achieve the result in the example above :
import React from 'react';
import { useMessages } from '@ollie-shop/react';
function NotificationSystem() {
const { messages, addMessage, clearAll } = useMessages();
// Create a success message
const handleSuccess = () => {
addMessage({
type: 'success',
title: 'Order Placed',
content: 'Your order has been successfully placed.',
});
};
// Create an error message
const handleError = () => {
addMessage({
type: 'error',
content: 'Unable to process your request. Please try again.',
});
};
return (
<div>
<button onClick={handleSuccess}>Place Order</button>
<button onClick={handleError}>Test Error</button>
{messages.length > 0 && (
<button onClick={clearAll}>Clear All Messages</button>
)}
</div>
);
}
Examples per Action
addMessage(message)
Adds a new message to the message stack.
Parameters
addMessage({
type: 'success',
title: 'Order Placed',
content: 'Your order has been successfully placed.'
});
removeMessage(messageId)
Removes a specific message from the stack by its ID.
Parameters
messageId
: id
of the message to remove
...
removeMessage('message-uuid-123');
...
Messages are self dismissed after 5 seconds, so you don’t need to do it manually.
clearAll()
Removes all messages from the message stack.