初心者向け!WindowsでReactNative入門~アプリ開発編~ 3日目

f:id:enia:20211005223434p:plain えにあです。

WindowsでReactNative入門~アプリ開発編~の3日目です。 前回はコードを修正するための前準備として、アプリのエントリポイントの変更を行いました。 今回は実際にアプリを修正していきます。

今回の目標

ニュースの一覧画面を作成する処理を分割して考えると、以下のようになります。

  1. News APIからニュースを取得する
  2. 取得したニュースの件数分ループを回す
  3. ニュースを1件ずつ表示する

今回は1の部分を実装します。

News APIのアカウント作成

まずはNews APIの公式サイトでアカウントを作成します。 newsapi.org

諸々入力して、利用規約に同意してSubmitを押下します。 f:id:enia:20211010172337p:plain

API Keyが表示されます。この値を後程使います。
マイページからいつでも確認できるので心配ありません。
f:id:enia:20211010172553p:plain

axiosのインストール

外部のAPIを呼び出す場合、基本的にはhttpsプロトコルを使ってコールします。 今回はHTTPクライアントとしてオープンソースのaxiosを使っていきます。

github.com

yarn add axiosを実行します。

PS D:\Learning\news-app> yarn add axios
yarn add v1.22.11
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.13: The platform "win32" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
info Direct dependencies
└─ axios@0.22.0
info All dependencies
├─ axios@0.22.0
└─ follow-redirects@1.14.4
Done in 8.87s.

これでaxiosのインストールは完了です。

ソースコードの修正

App.tsxに以下の行を追加します。

import axios from "axios";
const URL =  "https://newsapi.org/v2/top-headlines?country=jp&category=business&apiKey=168axxxxxxxxxxxxxxxxxxxxxxxxd3f4";
axios.get(URL).then((res) => console.log(res.data));

1行目はaxiosのimportです。インストールしたライブラリを利用する場合はこのようにimportを行う必要があります。 2行目はNewsAPIのURLです。最後のapiKeyの部分はアカウント作成時に割り振られたキーになります。 3行目はAPIのコールです。axios.get(URL)で、NewsAPIをコールしています。そして、返ってきた結果がresに格納されますので、そのresの中身を表示しています。

修正を保存して実行してみましょう。 expoを実行しているターミナルに、以下のようなログが表示されるはずです。

Object {
  "articles": Array [
    Object {
      "author": null,
      "content": null,
      "description": "埼玉県のJR蕨交流変電所で火災が発生しました。この影響とみられる停電で、山手線、京浜東北線、埼京線、常磐線の快速などJR東日本管内の多くの路線で運転を見合わせています。 消防によりますと、10日
午後0時50分すぎ、近所の人などから「変電所で爆発音が聞こえ、火災が発生した」と通報が入りました。「雷のような音がして、...",
      "publishedAt": "2021-10-10T05:26:02Z",
      "source": Object {
        "id": null,
        "name": "YouTube",
      },
      "title": "埼玉県のJR変電所で火災 複数路線で運転見合わせ(2021年10月10日) - ANNnewsCH",
      "url": "https://www.youtube.com/watch?v=6pDVwy4hTAM",
      "urlToImage": "https://i.ytimg.com/vi/6pDVwy4hTAM/hqdefault.jpg",
    },
・・・

NOTE:
ログが表示されない場合はexpoを実行しているターミナルで r を押すとリロードされて正しく表示されることがあります。変更が反映されないなと思ったら、expoやエミュレータを落とし上げしたり、rを押してみたり、色々試してみましょう。

結果を見ると、title、author、urlToImageあたりが画面表示に使えそうだな、とうことが分かります。

APIキーをファイルに外だしする

さて、先ほどのソースではURLの中にAPIキーを直書きしましたが、このような定数は設定ファイルに外だしするのが一般的です。

Expoで定数を利用するにはExpoConstantsを利用します。 docs.expo.dev

ドキュメントにあるようにexpo install expo-constantsでインストールします。

PS D:\Learning\news-app2> expo install expo-constants
Installing 1 SDK 42.0.0 compatible native module using Yarn.
> yarn add expo-constants@~11.0.1
yarn add v1.22.11
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.13: The platform "win32" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ expo-constants@11.0.1
info All dependencies
└─ expo-constants@11.0.1
Done in 23.13s.

定数はapp.jsonに記載します。app.jsonの最後に以下を追加します。

    "extra": {
      "newsApiKey": "168axxxxxxxxxxxxxxxxxxxxxxxxd3f4"
    }

最後にソースコードから定数をapp.jsonに記載した定数を読み込みます。App.tsxを以下のように修正します。

import Constants from "expo-constants";
import axios from "axios";
const URL = `https://newsapi.org/v2/top-headlines?country=jp&category=business&apiKey=${Constants.manifest?.extra?.newsApiKey}`;
axios.get(URL).then((res) => console.log(res.data));

1行目でインストールしたライブラリをimportしています。 3行目で、Constants.manifest?.extra?.newsApiKeyでapp.jsonに記載したAPIキーを設定しています。extra以降がapp.jsonに追記した内容が設定されます。

さて、これで再度実行してみます。

まとめ

  • NewsAPIを使って、Newsデータの一覧を取得する方法を学びました
  • 定数をapp.jsonに外だしし、アプリから読み込む方法を学びました

今回はここまで!