0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Inertia Router と axios の違い・役割・注意点まとめ

Posted at

はじめに

Laravel × Inertia.js × React(または Vue/Svelte)の開発では、サーバーとの通信に

  • Inertia Router
  • axios

の両方がよく登場します。

今回は、私がそれぞれの特徴をあまり理解していなかったために起きたエラーを解決する際に、学んだことをまとめていきます。


axiosとは?

JavaScript の汎用 HTTP クライアントライブラリです。
GET / POST / PUT / DELETE などのリクエストを簡単に送信でき、レスポンス処理は自分で実装する必要があります。

特徴

  • 汎用的にどんな API でも叩ける
  • レスポンスが JSON ならそのまま response.data で扱える
  • ページ遷移や props 更新は自分で書かないといけない
コード例
import axios from 'axios'
import { useEffect, useState } from 'react'

export default function PostList() {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    axios.get('/api/posts')
      .then(res => setPosts(res.data))
  }, [])

  return (
    <ul>
      {posts.map(post => <li key={post.id}>{post.title}</li>)}
    </ul>
  )
}

Inertia Router とは?

Inertia.js が提供する SPA的なページ遷移用の通信 API です。
内部的には XHR/Fetch を使っていますが、単なる通信ではなく ページ遷移や props 更新を自動で行う のが特徴です。

特徴

  • サーバーからのレスポンスは Inertia ペイロード(component, props, url, version を含む JSON) を想定

  • 成功すると自動的にページを再描画し、SPA 的な体験を実現

  • router.post, router.put, router.delete などのメソッドを提供

コード例
import { router } from '@inertiajs/react'
import { useState } from 'react'

export default function CreatePost() {
  const [title, setTitle] = useState('')

  const submit = (e) => {
    e.preventDefault()
    router.post('/posts', { title })
  }

  return (
    <form onSubmit={submit}>
      <input value={title} onChange={e => setTitle(e.target.value)} />
      <button type="submit">Save</button>
    </form>
  )
}

axios と Inertia Router の違い

項目 axios Inertia Router
主な役割 汎用 HTTP クライアント Inertia ページ遷移・フォーム送信
レスポンス JSON など何でもOK Inertia ペイロード必須
画面更新 自分で実装 自動で props 更新 & 再描画
適用範囲 外部API・API専用ルート Inertia::render を返すルート

注意点

1. Inertia Router で JSON API を叩かない

Inertia Router は Inertia ペイロードを期待しているため、通常の JSON API を返すとエラーになります。

ちなみに、私もこれでエラーが出てしまいました。。。

2. 使い分けを明確にする

ページ遷移やフォーム送信 → Inertia Router
JSON 取得や外部 API → axios

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?