Tutorial

React でAxios を使用する方法

Published on December 15, 2020
日本語
React でAxios を使用する方法

はじめに

Web 上の多くのプロジェクトは、開発の段階の一部で REST API とインターフェイスする必要があります。Axiosは、Angular.jsバージョン1系の$httpサービスに基づく軽量HTTPクライアントであり、ネイティブJavaScriptの Fetch API に似ています。

Axios は promiseベースであり、非同期コードをより読みやすくするために、JavaScript のasyncおよびawaitを活用することができます。

リクエストを傍受してキャンセルすることもでき、クロスサイトリクエストフォージェリに対するクライアント側の保護機能が組み込まれています。

この記事では、Axiosを使用して、Reactアプリケーション内の一般的な JSONプレースホルダーAPI にアクセスする方法の例を説明します。

前提条件

この記事を進めるには、次のものが必要です。

ステップ1 — プロジェクトにAxiosを追加する

このセクションでは、Create React Appを使用してReactプロジェクトをセットアップする方法のチュートリアルに従って作成したdigital-ocean-tutorial React プロジェクトにAxiosを追加します。

プロジェクトにAxios を追加するには、ターミナルを開き、ディレクトリをこのプロジェクトに変更します。

  1. cd digital-ocean-tutorial

その後、このコマンドを実行してAxiosをインストールします。

  1. npm install axios

次に、Axios を使用するファイルにインポートする必要があります。

ステップ2 — GET リクエストを実行する

この例では、新しいコンポーネントを作成し、そのコンポーネントにAxios をインポートしてGET リクエストを送信します。

React プロジェクトの src フォルダ内に、PersonList.js という名前のコンポーネントを作成します。

  1. nano src/PersonList.js

次のコードをコンポーネントに追加します。

digital-ocean-tutorial/src/PersonList.js
import React from 'react';

import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      <ul>
        { this.state.persons.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}

まず、React と Axios をインポートして、両方をコンポーネントで使用できるようにします。次に、componentDidMount のライフサイクルフックを使用して、GET リクエストを実行します。

axios.get(url)をAPI エンドポイントのURL と組み合わせて使用すると、応答オブジェクトを返すpromiseを取得します。応答オブジェクト内には、personの値が割り当てられるデータがあります。

res.status を基にステータスコードや、res.request 内の詳細情報など、リクエストに関するその他の情報を取得することもできます。

ステップ3 — POST リクエストを実行する

このステップでは、POSTと呼ばれる別のHTTPリクエストメソッドを使用してAxiosを使用します。

PersonList 内の前のコードを削除し、次のコードを追加してユーザー入力可能なフォームを作成し、その後コンテンツをAPIに POST します。

digital-ocean-tutorial/src/PersonList.js

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

export default class PersonList extends React.Component {
  state = {
    name: '',
  }

  handleChange = event => {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    const user = {
      name: this.state.name
    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

handleSubmit関数内で、フォームのデフォルトの動作を無効にします。その後、stateuser入力に更新します。

POSTを使用すると、thenコール内で使用できる情報を含む同じ応答オブジェクトを取得できます。

POSTリクエストを完了するには、まず、user入力をキャプチャします。次に、POSTリクエストと共に入力を追加すると、応答が得られます。次に、console.log 応答を使用して、フォームに user 入力を表示できます。

ステップ4 — DELETE リクエストを実行する

この例では、axios.deleteを使用して API から項目を削除し、URLをパラメータとして渡す方法を説明します。

フォームのコードをPOST の例から変更して、新しいユーザーを追加する代わりにユーザーを削除します。

digital-ocean-tutorial/src/PersonList.js

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

export default class PersonList extends React.Component {
  state = {
    id: '',
  }

  handleChange = event => {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person ID:
            <input type="text" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}

この場合も、res オブジェクトは、リクエストに関する情報を提供します。その後、フォームの送信後に、console.log にその情報を再度表示できます。

ステップ5 — Axios で Baseインスタンスを使用する

この例では、URLとその他の設定要素を定義できる_baseインスタンス_を設定する方法を説明します。

api.js という名前の別のファイルを作成します。

  1. nano src/api.js

次のデフォルトを使用して、新しいaxios インスタンスをエクスポートします。

digital-ocean-tutorial/src/api.js
import axios from 'axios';

export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});

デフォルトインスタンスを設定すると、PersonList コンポーネント内で使用できるようになります。次のように新しいインスタンスをインポートします。

digital-ocean-tutorial/src/PersonList.js
import React from 'react';
import axios from 'axios';

import API from '../api';

export default class PersonList extends React.Component {
  handleSubmit = event => {
    event.preventDefault();

    API.delete(`users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }
}

http://jsonplaceholder.typicode.com/ が、ベース URL になっているため、APIで別のエンドポイントにアクセスするたびにURL全体を入力する必要がなくなりました。

ステップ6 — async および await を使用する

この例では、promiseを処理するために、async およびawait の操作方法を説明します。

await キーワードは、promiseを解決しを返します。その後、を変数に割り当てることができます。

handleSubmit = async event => {
  event.preventDefault();

  //
  const response = await API.delete(`users/${this.state.id}`);

  console.log(response);
  console.log(response.data);
};

このコードサンプルでは、.then() が置き換えられています。promiseは解決され、値はresponse変数内に格納されます。

まとめ

このチュートリアルでは、Reactアプリケーション内でAxiosを使用してHTTPリクエストを作成し、応答を処理する方法の例をいくつか見てきました。

Reactについての詳細については、React.js でのコーディング方法シリーズを参照するか、またはReact トピックページでより多くの演習とプログラミングプロジェクトをご覧ください。

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel