LoginSignup
7
2

More than 1 year has passed since last update.

【JavaScript】Uncaught TypeError: Cannot read properties of undefined (reading 'dates')

Last updated at Posted at 2022-04-28

問題点

JavaScriptのコードを書いている該当ページ以外のページに移動すると、下記のエラーが出る。

console
Uncaught TypeError: Cannot read properties of undefined (reading 'dates')

エラー文の意味

TypeErrorとあるので、タイプミスをしているのか?
と思ったが、どうやら違うよう。

その後の文が重要。
Cannot read properties of undefined (reading 'dates')
未定義のプロパティを読み取ることができません(reading 'dates')

直訳すると上記ですが、ニュアンス的には下記が正しいらしい。
undefinedに対してdatesというプロパティは読み込めません
ここではundefinedが何なのかが重要。

ということで調べてみると、、、
undefinedは下記の実際のコード中の定数datasetに値することがわかった。

「undefinedな値に対して何かプロパティにアクセスしようとした時に、そんなアクセスは不可能ですと教えてくれるのが、このエラーの本質的な意味」だそうです。←参考

実際のコード

application.js
document.addEventListener('turbolinks:load', () => {
  const dataset = $('#condition-show').data()
  const dates = dataset.dates ←ここでエラーが出ている
  axios.get(`/conditions/${dates}.json`)
     .then((res) => {

        以下省略

コードの2行目の定数datasetがundefinedになっているため、

3行目のdataset.datesの箇所でundefined(dataset)に対してdatesというプロパティは読み込めませんというエラーが出てしまっている。

問題点における原因

当初の問題点に戻ると、

JavaScriptのコードを書いている該当ページ以外のページに移動するとエラーが出る。
ということでしたが、
この原因は、他のページでは定数datasetの値が存在しないためdatasetがnullになってしまう。
ということがわかりました。

解決策

application.js
document.addEventListener('turbolinks:load', () => {
    const dataset = $('#condition-show').data()
  if (!dataset){ return false; }これを追加
  const dates = dataset.dates
  axios.get(`/conditions/${dates}.json`)
    .then((res) => {

    以下省略

if (!dataset){ return false; }

上記を追加することで、datasetがnullの場合にそれ以降のコードを読み込まないようにしてくれます。

参考

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