Search results

Prevent duplicate Toast display

You can prevent identical same toast displaying in a screen by event function. You can terminate the toast displaying process by setting cancel event property in beforeOpen Event.

Here below sample demonstrates preventing duplicate title Toast element displaying, with custom code blocks.

Source
Preview
index.tsx
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import { ToastBeforeOpenArgs, ToastComponent } from '@syncfusion/ej2-react-notifications';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default class ReactApp extends React.Component<{}, {}> {
  public toastInstance: ToastComponent;
  public toasts = [
    { title: 'Warning !', content: 'There was a problem with your network connection.' },
    { title: 'Success !', content: 'Your message has been sent successfully.' },
    { title: 'Error !', content: 'A problem has been occurred while submitting your data.' }
  ];
  public toastFlag: number = 0;
  public prevDuplicates: boolean;
  public timeOutDelay: number = 600;
  public position = { X: 'Center' };

  public toastCreated(): void {
    this.toastInstance.show(this.toasts[this.toastFlag]);
    ++this.toastFlag;
  }

  public toastShow() {
    setTimeout(
      () => {
        this.toastInstance.show(this.toasts[this.toastFlag]);
        ++this.toastFlag;
        if (this.toastFlag === (this.toasts.length)) {
          this.toastFlag = 0;
        }
      }, this.timeOutDelay);
  }

  public btnClick(): void {
    this.toastShow()
  }
  public onBeforeOpen(e: ToastBeforeOpenArgs): void {
    e.cancel = this.preventDuplicate(e);
  }
  public preventDuplicate(e: ToastBeforeOpenArgs): boolean {
    let i: number = 0;
    const toastEle: HTMLElement = e.element;
    const toasts: HTMLCollection = e.toastObj.element.children;
    while (toasts.length) {
      if (!toasts && toasts[i].querySelector('.e-toast-title').isEqualNode(toastEle.querySelector('.e-toast-title'))) {
        return true;
      }
      i++;
    }
    return false;
  }

  public render() {
    return (
      <div>
        <ButtonComponent cssClass="e-primary" onClick={this.btnClick = this.btnClick.bind(this)}> Show Toast </ButtonComponent>
        <ToastComponent ref={toast => this.toastInstance = toast!} position={this.position} beforeOpen={this.onBeforeOpen = this.onBeforeOpen.bind(this)} created={this.toastCreated = this.toastCreated.bind(this)} />
      </div>
    );
  }
}
ReactDOM.render(<ReactApp />, document.getElementById('element'));