0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Emailのプレビュー機能がレンダリングに失敗し、サーバーごと止まる

0
Posted at

ケース

React Emailを使っていて、

$ npm run email:dev

> app@0.1.0 email:dev
> email dev --dir src

    React Email 5.2.5
    Running preview at:          http://localhost:3000

  ✔ Ready in 0.2s

  ✖ Rendering email template Foobar.tsx

のようになって、停止してしまうことがあります。
加えて、エラーが出ないため、原因の特定がとても難しくなります。

原因

私の場合は、引数の配列にundefinedを渡されていることが原因でした。
これにより、.json()しているのにundefinedが渡され、レンダリングが失敗してしまいます。
レンダリングに失敗すると、何故かReact Emailではプレビュー用のサーバーが止まってしまいます。

対策

このような場合、.reduce().map()を代用したアプローチでは問題を解決できません。
ではどうするかというと、先にundefinedではないかを判定します。
propsに引数を入れているとすると、

const piyo = props.array !== undefined ? props.array.join(",") : "データなし";

のようにすることで解決できます。

応用的なアプローチとして、Typescriptでは型チェックがあるので、必須引数がundefinedならプレビューであると言えます。このため、undefinedならダミーデータを入れる、ということができます。

実際のコードで例を示すと、

// React EmailのPreviewは必須の配列に対してもundefinedを渡すので、Previewかどうかの判定を行う
// プレビューなら、ダミーデータを入れる
if (items === undefined) {
    console.log("プレビューです");
    safeItems = [
        // ダミーデータをここに入れる
    ];
  }

のようにして使うことができます。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?