UNPKG

stackpress

Version:

Incept is a content management framework.

77 lines (76 loc) 2.34 kB
import { useContext } from 'react'; import UniversalCookie from 'universal-cookie'; import { toast } from 'react-toastify'; import NotifyContext, { config } from './NotifyContext.js'; const cookieConfig = { path: '/' }; const cookie = new UniversalCookie(); export function notify(type, message, autoClose) { if (!autoClose) { autoClose = config.autoClose || 5000; } const options = { ...config, autoClose }; switch (type) { case 'info': toast.info(message, options); break; case 'warn': toast.warn(message, options); break; case 'error': toast.error(message, options); break; case 'success': toast.success(message, options); break; } } export function flash(type, message, close = 5000) { cookie.set('flash', JSON.stringify({ type, message, close }), cookieConfig); } ; export function unload() { const value = cookie.get('flash'); if (value) { cookie.remove('flash', cookieConfig); const args = typeof value === 'string' ? JSON.parse(value) : value; notify(args.type, args.message, args.close); } } ; export function useNotify() { const { config } = useContext(NotifyContext); const handlers = { notify(type, message, autoClose) { if (!autoClose) { autoClose = config.autoClose || 5000; } const options = { ...config, autoClose }; switch (type) { case 'info': toast.info(message, options); break; case 'warn': toast.warn(message, options); break; case 'error': toast.error(message, options); break; case 'success': toast.success(message, options); break; } }, flash, unload() { const value = cookie.get('flash'); if (value) { cookie.remove('flash', cookieConfig); const args = JSON.parse(value); handlers.notify(args.type, args.message, args.close); } } }; return handlers; }