4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

axiosを使ってReactでUnsplash APIを叩いてみた

Last updated at Posted at 2019-01-29

概要

今回はaxiosを使って外部APIを叩いてみたいと試みます。

Unsplashについて

外部APIとして使ったUnsplashというのはサンプル画像を提供している場所です。
これを使い、ボタンをクリックしたら写真一覧が表示されるといったものを作っていきます。

詳細

https://unsplash.com/developers

コードを書いていく

とりあえずcreate-react-appでディレクトリを作成して、axiosをインストールします。

create-react-app react-unsplash
cd react-unsplash
npm install --save axios
npm start

次にindex.jsはこちらになります。
今回の構成要素としてはデータを取得しstateに保存するApp.jsと、そのデータを表示するImageList.jsになります。

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(
  <App />,
  document.querySelector('#root')
);

次にApp.jsはこちらになります。

src/components/App.js
import React, { Component } from 'react'
import ImageList from './ImageList';

class App extends Component {
  state = { images: [] };

  getPhotos = () => {
    //apiからデータを取得してstateに保存する処理
  }

  render() {
    return (
      <div>
        <input 
          type="button" 
          value='get photos'
          onClick={this.getPhotos}
        />
        <ImageList images={this.state.images} />
      </div>
    );
  }
}

上記のコードからボタンをクリックしたらgetPhotosが呼ばれ、そこでデータを取得してstateに保存し、ImageListで表示するというイメージがわかると思います。

次にUnsplashと通信する処理を書いていきます。

ここでaxiosを使うのですが、axiosにはcreateやgetといったメソッドがあるのですが今回はデータを取得するgetメソッドを使っていきます。これは第一引数にエンドポイント、第二引数にパラメーターや認証情報を書いていきます。
以下、getPhotos関数のコードになります。

import axios from 'axios';

getPhotos = async () => {
  const response = await axios.get("https://api.unsplash.com/photos", {
    headers: {
      Authorization: "Client-ID YOUR_ACCESS_KEY" //YOUR_ACCESS_KEYは登録時に取得できる
    }
  });

  this.setState({ images: response.data });
}

非同期通信はasync/awaitで書いています。
また、bindする必要があるのでアロー関数で書いています。

以下、App.jsの全コードです。

src/components/App.js
import React, { Component } from 'react';
import axios from 'axios';
import ImageList from './ImageList';

class App extends Component {
  state = { images: [] };

  getPhotos = async () => {
    const response = await axios.get("https://api.unsplash.com/photos", {
      headers: {
        Authorization: "Client-ID YOUR_ACCESS_KEY"
      }
    });
    
    this.setState({ images: response.data});
  }

  render() {
    return(
      <div>
        <input 
          type="button" 
          value='get photos'
          onClick={this.getPhotos}
        />
        <ImageList  images={this.state.images} />
      </div>
    );
  }
}

export default App;

最後にImageList.jsで表示します。

src/components/ImageList.js
import React from 'react';

const ImageList = (props) => {
  const images = props.images.map(image => {
    return <img key={image.id} src={image.urls.regular} alt={image.description} />;
  });

  return (
    <div>
      {images}
    </div>
  );
}

export default ImageList;

.dataや.id、.urlsなどはconsole.log(response);で調べていくとどういったデータが帰ってきているのかわかるので、そこから取っています。
あとはstateの配列をmapで回して写真一覧を表示する、といった流れになります。

まとめ

今回はaxiosを使って外部APIとの通信を行いました。
getメソッドしか使っていないので今後色々試してみたいと思います。
他にも面白い外部APIはあると思うのでたくさん触っていきたいと思います。

4
8
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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?