Open
Description
Which problem do we want to solve
- Starting from https://mui.com/toolpad/core/react-use-notifications/
- Want to be able to fire notifications globally, from e.g. zustand store. See https://discord.com/channels/1131323012554174485/1248515176626524200/1330240821676474473
- Do want to handle edge-cases?
- The user fires notifications before the UI is mounted or after it’s unmounted. Should it error? or queue? Should it time out?
How do we solve the problem
API
We maintain API parity for the existing solution but manage the state outside of react. a Global api to create a notifications instance that includes open
/ close
methods, and a provider that must be rendered by the user. The user can create their own instance, or use a global one we also provide.
interface NotificationsApi {
// Original methods
open(...)
close(...)
Provider: React.ComponentType<{}>
}
// Allow users creating their own instance
export function createNotifications(options): NotificationsApi;
// Provide global default instance
const { open, close, Provider } = createNotifications()
export { open, close, Provider }
// backwards compatibility
export function useNotifications() {
return { open, close }
}
User can then use it in their zustand store as such:
import { create } from 'zustand'
import * as notifications from '@toolpad/core/notifications'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => {
set((state) => ({ bears: state.bears + 1 }))
notifications.show('One more bear', {})
},
removeAllBears: () => set({ bears: 0 }),
updateBears: (newBears) => set({ bears: newBears }),
}))
Edge-case
When no UI is rendered, notifications are queued. As soon as UI is rendered queued notifications are shown. It’s the responsibility of the user to have the provider rendered. If it turns out problematic we can consider adding a warning in dev if we detect:
- The UI has unmounted and notifications are enqueue
- The UI has never mounted and notifications have been enqueued for longer than X milliseconds.
but let's await user feedback first.