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 Native 「`」バッククォートでないと失敗するケース

Posted at

APIを利用する上でAPIKeyを「.env」ファイルに記述してそこから呼び出す仕様としたが、ここで躓いてしまった。

「`バッククォート」「'シングルクォーテーション」「"ダブルクォーテーション」での使い分けを理解していないために日を跨いで試行錯誤することになった。

失敗.tsx
const responce = await axios.get('https://newsapi.org/v2/everything?q=keyword&apiKey=${process.env.EXPO_PUBLIC_NEWS_API_KEY}');
成功.tsx
const responce = await axios.get(`https://newsapi.org/v2/everything?q=keyword&apiKey=${process.env.EXPO_PUBLIC_NEWS_API_KEY}`);

原因は「`」バッククォートと「'」シングルクォーテーションの違い。

これまでネット上にあるコードを参考にしてやってきたけど、例えば「'」部分を「"」で記述する等の違いがあっても問題なく動いたため気にせずにここまで来てしまった。
変数の呼び出しを含む場合には「`」バッククォートで囲むとか文法上のルールがあるのかもしれない。

〜原因を突き止めるのに時間を要した理由〜
「'」シングルクォーテーションで囲った状態で「APIKey」を直接記述して情報を取得できるか試したところ上手くいったため、変数に書き換えた途端に失敗した原因を別の部分に求めてしまった。

実は「.env」ファイルで管理する場合は先頭に「EXPO_PUBLIC_」をつけるという変数名のルールも理解できていなかった。

0
0
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
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?