UNPKG

react-native-toastier

Version:

A Fully Customizable Toast Component for React Native.

93 lines 2.85 kB
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } import React, { createContext, useCallback, useEffect, useMemo, useState } from 'react'; import Toast, { defaultDuration } from '../Toast'; import { View } from 'react-native'; import styles from './styles'; const noop = () => undefined; const defaultValue = { show: noop, showError: noop, showWarning: noop, showInfo: noop, clear: noop }; export let ToastService = defaultValue; export const ToastContext = /*#__PURE__*/createContext(defaultValue); const ToastProvider = ({ children, theme, ...props }) => { const [routeName, setRouteName] = useState(null); const [toast, setToast] = useState(null); const [toastTimeOutId, setToastTimeOutId] = useState(); const onClose = useCallback(() => { toast?.onClose?.(); setToast(null); }, [toast]); const clearToastTimeOut = useCallback(() => { if (toastTimeOutId) { clearTimeout(toastTimeOutId); } }, [toastTimeOutId]); const setToastTimeOut = useCallback(() => { const timeOutId = setTimeout(() => { onClose(); }, defaultDuration); setToastTimeOutId(timeOutId); }, [setToastTimeOutId]); const setToastData = (type, params) => { clearToastTimeOut(); setToast({ type, ...params }); setToastTimeOut(); }; const value = useMemo(() => { return { show: params => { setToastData('success', params); }, showError: params => { setToastData('danger', params); }, showWarning: params => { setToastData('warning', params); }, showInfo: params => { setToastData('info', params); }, clear: () => { clearToastTimeOut(); setToastTimeOut(); setToast(null); }, routeName, toast, setRouteName }; }, [routeName, toast, clearToastTimeOut, setToastTimeOut]); useEffect(() => { ToastService = value; return () => { ToastService = defaultValue; clearToastTimeOut(); }; }, [value]); return /*#__PURE__*/React.createElement(View, { style: [styles.styles.container, props.providerContainerStyle].flat() }, /*#__PURE__*/React.createElement(ToastContext.Provider, { value: value }, children, /*#__PURE__*/React.createElement(Toast, _extends({ message: "" }, toast, { open: Boolean(toast), onClose: onClose, theme: theme, children: props.toast || toast?.children, offset: props.offset }, props)))); }; export default ToastProvider; //# sourceMappingURL=ToastProvider.js.map