Lightning コンポーネント開発 TIPS: Toast の使い方と注意点


さて、今回は Lighting の基本コンポーネントにある Toast についてです。
処理の完了やエラーメッセージの表示など利用用途は多岐にわたるコンポーネントですが、一部利用できないケースもあるので対処方法を合わせてご紹介します。
Lightning Component Library - Show Toast

トーストの使い方

まずは、トーストの基本的な使い方です。以下は ErrorToastExample という Lightning バンドルを作成し、「エラー」ボタンを押すとエラーメッセージが表示されるだけのサンプルコードです。

ErrorToastExample.cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    <div>
        <lightning:button variant="destructive" label="エラー" onclick="{!c.onClick}"/>
    </div>
</aura:component>
ErrorToastExampleController.js
({
    onClick : function(c, e, h) {
        h.showError(c, h, "エラーだよ!");
    }
})
ErrorToastExampleHelper.js
({
    showError : function(c, h, message) {
        const event = $A.get("e.force:showToast");
        event.setParams({
            type: "error",
            mode : "sticky",
            message: message,
        });
        event.fire();
    }
})

トーストが利用できないケースと対処法

非常に簡単に使えるトーストなのですが、以下のようなケースでは表示されないので注意してください。

  • コンポーネントのレンダリングが完了していない初期化時や
  • イベントが処理できない Lightning アプリケーションビルダーでのページ編集時

つまり、トーストを表示できない状況でもメッセージを表示出来るように対処しておく必要があります。

以下のコードはその対処例です。
メッセージを表示する際にトーストの表示可否を判定し、出来る場合はトーストを表示します。
出来ない場合は、コンポーネント変数に格納しておきレンダリング処理にまかせてコンポーネント内に表示します。

ErrorToastExample.cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >

       <!-- Private Attributes -->
    <aura:attribute name="message" type="String" access="private" />  

    <!-- Event Handler -->
    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />

    <!-- User Interface -->
    <div aura:id="component">
        <aura:if isTrue="{!!empty(v.message)}">
            <ui:message title="{!v.message}" severity="error" closable="false" />
        </aura:if>

        <lightning:button variant="destructive" label="エラー" onclick="{!c.onClick}"/>
    </div>
</aura:component>
ErrorToastExampleController.js
({
    onInit : function(c, e, h) {
        h.showError(c, h, "初期化時のエラーだよ!");
    },
    onClick : function(c, e, h) {
        h.showError(c, h, "ボタン押下時のエラーだよ!");
    },
})
ErrorToastExampleHelper.js
({
    showError : function(c, h, message) {
        const isEditor = document.location.href.toLowerCase().indexOf("flexipageeditor") >= 0;
        const isRendered = c.find("component").getElement();
        if (isEditor || !isRendered) {
            // レンダリングが完了していない場合やアプリケーションビルダーでの編集時は変数への格納だけ行う。
            // 格納されたメッセージは再レンダリング処理で画面上に表示される。
            c.set("v.message", message);
        } else {
            const event = $A.get("e.force:showToast");
            event.setParams({
                type: "error",
                mode : "sticky",
                message: message,
            });
            event.fire();
        }
    }
})

少し格好は悪いですが、こうすればページ編集時や初期化時の処理に発生したメッセージも画面に表示する事ができるようになります。