LoginSignup
11
8

React×Railsの連携におけるPromiseベースのHTTPクライアント"Axios"使用法

Last updated at Posted at 2024-04-10

未経験エンジニアの備忘録です。
間違えている箇所がありましたらご教示頂けると幸いです。

Axiosとは

Axiosは、node.jsを使用してHTTPリクエストを行うHTTPクライアントになります。
PromiseAPIもサポートしており非同期処理でサーバーサイドからデータを受け取る際に有用です。

データやり取りの順序

①クライアントにてXMLHttpRequestを作成
②node.jsにてHTTPリクエストを行う
③Rails側からデータを受け取る

主な実装方法(Rails側ではgem"Rack-CORS"を使用してCORSを許可しておくこと)

ex)POSTモデル一覧(postsテーブルからpostscontrollerのindex)を取得したい場合

①axiosのインスタンスを作成(インスタンスメソッドが使用可能になります)

client.js
import applyCaseMiddleware from 'axios-case-converter';
import axios from 'axios';

const client = applyCaseMiddleware(
  axios.create({
    baseURL: 'http://localhost:3000', //Rails側のlocalURL
  })
);

②axiosのgetインスタンスメソッドを用いてhttp://localhost:3000/postsのデータを取得

post.js
import client from './client';

export const getList = () => {
  return client.get('/posts');  //Rails側のroute.rbのルーティング
};

③取得したデータを基にList.jsxにhtmlのひな型を記載
今回はuseEffectの依存配列を空にすることでhandleGetListが実行されpost.jsのデータを取得、初回のみレンダリングされます。

List.jsx
import React, {useEffect, useState} from 'react';
import { getList } from '../lib/api/post';

const List = () => {
  const [dataList, setDataList] = useState([]);

  useEffect(() => {
    handleGetList();
  }, [])

  const handleGetList = async () => {
    try {
      const res = await getList();
      setDataList(res.data)
      } catch (e) {
      console.log(e);
      };
    }

  return (
    <>
    <h1>投稿リスト。</h1>
    <table border='7' cellspacing='5' cellpadding='3' width='500'>
      <tr>
        <th>ID</th>
        <th>タイトル</th>
        <th>内容</th>
      </tr>
      {
        dataList.map((data, index) => (
          <tr key={index}>
            <td>{data.id}</td>
            <td>{data.title}</td>
            <td>{data.content}</td>
          </tr>
        ))
      } 
      </table>
    </>
  );
};

簡単な流れは以上になります。axiosのインスタンスメソッドにはもちろんget,post,patch,delete以外にも様々なメソッドがありますので、まだまだ自分も把握できていませんが気になる方はぜひ使ってみてください。

11
8
4

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