Skip to main content

Toasts

This service provides utilities for displaying toast messages.

Displaying Toast Messages

There are four types of toast messages with corresponding functions to trigger them:

  • Success: successToast
  • Warning: warningToast
  • Error: errorToast

When creating a toast message, one can provide a title and optional subtitle as shown here:

import { errorToast, successToast } from '@rhapsody/toasts'

successToast('Done', 'The action completed successfully.')
errorToast('Action failed')

Alternatively, toasts can be created with an options object. This is useful when one wants to provide an additional action for the toast, or a callback that will fire once the toast is closed/auto-dismissed.

import { successToast, warningToast } from '@rhapsody/toasts'

successToast({
title: 'Background task started',
actionText: 'Stop',
actionCallback: () => console.log('"Stop" button clicked'),
})

warningToast({
title: 'Network connection issues',
subtitle: 'Some activities may not succeed.',
onCloseCallback: () => console.log('Toast closed/auto-dismissed'),
})

subscribeToToasts

Advanced: Subscribe to Toast Messages

caution

This operation should only be done by the platform.

We can subscribe to toast messages to display them in the appropriate location.

import React, { useEffect, useState } from 'react'
import { subscribeToToasts, ToastMessage } from '@rhapsody/toasts'
import { Toast } from './Toast'

const useToasts = () => {
const [messages, setMessages] = useState<ToastMessage[]>([])
useEffect(() => {
const unsubscribe = subscribeToToasts((newMessages) => {
setMessages(newMessages)
})
return unsubscribe
}, [])

return messages
}

export const ToastMessages = () => {
const messages = useToasts()

return (
<>
{messages.map((message) => (
<Toast
actionCallback={message.actionCallback}
actionText={message.actionText}
closeToastCallback={message.closeToast}
subtitle={message.subtitle}
title={message.title}
variant={message.variant}
/>
))}
</>
)
}