1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【gantt-task-react】空配列エラー:Cannot read properties of undefined (reading 'start')

Posted at

はじめに

gantt-task-reactを使ってReactでガントチャートを作成しています。
仮のデータでうまく動いていたものの、登録フォームから取得したデータに切り替えたところ、画面リロード時に以下のようなエラーが出るようになりました。

Cannot read properties of undefined (reading 'start')

このエラーは、gantt-task-react に渡しているタスクデータの中で start プロパティが undefined になっていることが原因です。

解決策

調べてみると gantt-task-reactタスクオブジェクトに必須プロパティ (id, name, type, start, end, progress)が1つでも欠けていたり、配列が空や undefined だったりすると、描画時にエラーを投げる ようです。

修正コード

描画前に、タスクデータが正しく揃っているか、かつ 空配列でないことをチェック するようにしました。
以下のように条件分岐を加えることで、エラーを防ぐことができます。

return (
    {ganttTasks.length > 0 ? (
        <Gantt tasks={ganttTasks} />
    ) : (
        <p>タスクを追加してください。</p>
    )}
)

おわりに

仮の配列から、実際の登録データを使うようにしたことで、エラーに遭遇しましたが、条件分岐を入れることで安全に描画できるようになりました。
今後もいろんなパターンを想定しながら、エラーのないアプリを目指して開発を進めていきます!

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてくださ!
▼▼▼

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?