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?

JSONPlaceholder から axios でデータを取得する

Posted at

JSONPlaceholderとは

テストやプロトタイピングのために提供される無料のREST APIです。GET, POST, PUT, PATCH, DELETEといったHTTPメソッドに対応しています。

特徴として、postscommentsalbumsphotostodosusersなどのエンドポイントがあり、簡単にデータを取得できます。たとえば、ブログ記事(posts)、ユーザー情報(users)、ToDoリスト(todos)などのデータがダミーで用意されています。

実際のAPIと同じ形式でデータを取得・送信できるため、本番環境のAPIに近い形でテストできるものです。バックエンドが準備できていない段階や、シミュレーションデータでテストしたいときに、ダミーのデータを使ってフロントエンドの実装を進めることができる便利なツールです。

※axiosの説明は割愛します

使用例

今回は、jsonplaceholder の Resources より user情報 を使用します。

まず、axiosをインポート。

App.js
import "./styles.css";
import axios from "axios";

export default function App() {
  const onClickUsers = () => {
    // getリクエストでデータを取得
    // .thenでデータ取得した後に実行する関数を設定
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        console.log(res.data);
      })
      // URLが正しくないなどの場合
      .catch((err) => {
        console.log(err);
      });
  };
  const onClickUser1 = () => {
    axios
      .get("https://jsonplaceholder.typicode.com/users?id=1")
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  return (
    <div className="App">
      <button onClick={onClickUsers}>users</button>
      <button onClick={onClickUser1}>id=1のuser</button>
    </div>
  );
}

onClickUsers
スクリーンショット 2024-10-22 0.38.22.png

onClickUser1
スクリーンショット 2024-10-22 0.38.36.png

https://jsonplaceholder.typicode.com/users/3
でも取得できます。
スクリーンショット 2024-10-22 0.42.30.png

以上です。とてもシンプル。

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?