Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Created October 19, 2021 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akiyamka/805a1c7372341f28cc461de89caa92fb to your computer and use it in GitHub Desktop.
Save Akiyamka/805a1c7372341f28cc461de89caa92fb to your computer and use it in GitHub Desktop.
import { createAtom } from '@reatom/core';
export type NotificationType = 'error' | 'warning' | 'info';
interface NotificationMessage {
title: string;
text?: string;
}
interface Notification {
id: number;
type: NotificationType;
message: NotificationMessage;
lifetimeSec: number;
onClose: () => void;
}
export const currentNotificationAtom = createAtom(
{
showNotification: (
type: NotificationType,
message: NotificationMessage,
lifetimeSec: number,
) => ({ type, message, lifetimeSec }),
removeNotification: (id: number) => id,
},
({ onAction, schedule, create }, state: Notification[] = []) => {
onAction('showNotification', ({ type, message, lifetimeSec }) => {
const id = performance.now();
const onClose= () => currentNotificationAtom.removeNotification.dispatch(id);
state = [...state, { id, type, message, lifetimeSec, onClose }];
schedule((dispatch) => {
setTimeout(onClose, lifetimeSec * 1000);
});
});
onAction('removeNotification', (idForDelete) => state = state.filter(({ id }) => id !== idForDelete));
return [ ...state ];
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment