はじめに
こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。
本日は React の axios について解説していきたいと思います
axios とは?
axiosは、HTTP 通信(API リクエストなど)を簡単に行うためのライブラリです。
React でデータを取得したり、サーバーに送信したいときによく使われます。
インストール
npm install axios
基本の使い方(GET リクエスト)
import axios from 'axios';
import { useEffect, useState } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
setPosts(res.data);
})
.catch((err) => {
console.error('エラー:', err);
});
}, []);
return (
<div>
{posts.map((post) => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
};
これは.then()と.catch()を使う一般的な例ですが、これをもっと読みやすくできるのが async/await です。
async/await を使った書き方
import axios from 'axios';
import { useEffect, useState } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchPosts = async () => {
try {
const res = await axios.get(
'https://jsonplaceholder.typicode.com/posts'
);
setPosts(res.data);
} catch (err) {
setError(err.message || 'エラーが発生しました');
} finally {
setLoading(false);
}
};
fetchPosts();
}, []);
if (loading) return <p>読み込み中...</p>;
if (error) return <p>エラー: {error}</p>;
return (
<div>
{posts.map((post) => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
};
export default App;
POST リクエストの例
const createPost = async () => {
try {
const res = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: '新しい投稿',
body: 'これはPOSTの例です',
userId: 1,
});
console.log('作成された投稿:', res.data);
} catch (err) {
console.error('投稿エラー:', err);
}
};
async/await を使うメリット
| 項目 | メリット |
|---|---|
| 可読性 | まるで同期処理のように読めるので、ネストが減る |
| エラー処理が明確 | try/catch でわかりやすく管理できる |
| 状態管理との相性 | useState との併用が自然で書きやすい |
まとめ
- axios は HTTP 通信を簡単にするためのライブラリ
- async/await を使うと、より読みやすく・保守しやすいコードになる
- 状態(loading, error, data)をしっかり管理するのが実践的