UNPKG

@hackplan/polaris

Version:

Shopify’s product component library

40 lines (39 loc) 1.84 kB
import React, { useContext, useEffect, useRef } from 'react'; import { createUniqueIDFactory } from '@shopify/javascript-utilities/other'; import { Toast as AppBridgeToast } from '@shopify/app-bridge/actions'; import { DEFAULT_TOAST_DURATION, FrameContext } from '../Frame'; import { usePolaris } from '../../hooks'; const createId = createUniqueIDFactory('Toast'); export default React.memo(function Toast(props) { const id = useRef(createId()); const appBridgeToast = useRef(); const frame = useContext(FrameContext); const { appBridge } = usePolaris(); useEffect(() => { const { error, content, duration = DEFAULT_TOAST_DURATION, onDismiss, } = props; const toastId = id.current; if (appBridge == null && frame) { frame.showToast(Object.assign({ id: id.current }, props)); } else if (appBridge != null) { // eslint-disable-next-line no-console console.warn("Deprecation: Using `Toast` in an embedded app is deprecated and will be removed in v5.0. Use `Toast` from `@shopify/app-bridge-react` instead. For example, `import {Toast} from '@shopify/app-bridge-react';`"); appBridgeToast.current = AppBridgeToast.create(appBridge, { message: content, duration, isError: error, }); appBridgeToast.current.subscribe(AppBridgeToast.Action.CLEAR, onDismiss); appBridgeToast.current.dispatch(AppBridgeToast.Action.SHOW); } return () => { if (appBridge == null && frame) { frame.hideToast({ id: toastId }); } else if (appBridgeToast.current != null) { appBridgeToast.current.unsubscribe(); } }; }, [appBridge, frame, props]); return null; });