5
4

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 3 years have passed since last update.

axiosを使い、APIからデータを取得する

Last updated at Posted at 2020-03-13

概要

Reactにaxios導入し、UnsplashAPIからデータを取得しました。

axiosとは?

Promise based HTTP client for the browser and node.js

ブラウザもしくはnode.js上で動くPromiseベースのHTTPクライアントです。

Promise オブジェクトは非同期処理の最終的な完了処理(もしくは失敗)およびその結果の値を表現します。

メリット

fetchAPI より使い方が簡単

HTTPメソッド(CRUD)

  • Create → POST/PUT
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
  • Read → GET
axios.get(url[, config])
  • Update → PUT
axios.put(url[, data[, config]])
  • Delete → DELETE
axios.delete(url[, config])
  • それ以外のhead、opitonsなど使用頻度低いメソッドはここで割愛します

導入:React + UnsplashAPI + axios

  1. axiosをインストールする
    $ npm install axios

  2. UnsplashAPIにてアカウントを作成し、新しいappを作成し、Documentationを参考し、アクセスキーを取得する(API認証で使われるため) 参考:Using the Unsplash API

  3. GETメソッドを使い、UnsplashAPIの写真データを取得する

axios.get('https://api.unsplash.com/search/photos', {
      params: {
        query: term //ゲットしたいもの
      },
      headers: {
        Authorization: 'Client-ID YOUR_ACCESS_KEY' //UnsplashAPIのアクセスキーを置き換え
      }
    });
  }

1.Reactのprojectに導入し、クエリパラメータを’apple’を設定し、りんごの写真をゲットする
$ create-react-app my-app

App.js

import React from 'react';
import axios from 'axios';

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

  onSearchSumbit = async () => {
    const response = await axios.get('https://api.unsplash.com/search/photos', {
      params: {
        query: 'apple'
      },
      headers: {
        Authorization: 'Client-ID YOUR_ACCESS_KEY' //UnsplashAPIのアクセスキーを置き換え
      }
    });
    this.setState({ images: response.data.results });
  }

  componentDidMount(){
    this.onSearchSumbit();
  }

  render() {
    return (
      <div className="ui container" style={{marginTop: '10px'}}>
        GETしたデータの件数:{this.state.images.length}
        {this.state.images.map((image) => {
          return <img src={image.urls.regular} />;
        })}
      </div>
    );
  }
}

export default App;

結果

Screen Shot 2020-03-13 at 16.22.17.png

localhost_3000_ (1).png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?