10
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?

【超わかりやすい】fetch + then + mapで擬似的なAPIを取得してTodoを表示する処理を分解して解説してみた【JavaScript】

Last updated at Posted at 2025-12-05

はじめに

JavaScript の fetch を使って API からデータを取得し、それを HTML に描画するコードの動きがよく分からなかったので、詳しく解説してみました。

対象コードはこちら

function todo() {
  fetch('/serv/api/todo')
    .then(res => res.json())
    .then(json => {
      const html = json.todos.map(todo => `
        <li>${todo.title}</li>
      `).join('');
      list.innerHTML = html;
    });
}

*APIは擬似的なものです


何が行われているのか一言で言うと...

サーバーからTodoリストを取得 → <li>タグに変換 → 画面に表示

この処理が順番に書かれています。

1行ずつ細かく解説

1 : fetch('/serv/api/todo')

fetch('/serv/api/todo')

まだデータは受け取っていない!重要!
サーバーに「データちょうだい!」とリクエストを送ります。
ただしこの時点ではまだ返事は来ておらず、注文を出しただけの状態です。

だから次の処理をつづけるには.then()が必要になります!

thenは注文が届いた時にどうするかを予め決めておく非同期処理メソッド

2 : .then(res => res.json())

.then(res => res.json())

fetch の結果 res(レスポンス) を
JavaScript で使える JSON データに変換しています。

非同期処理なので .then() で続きの処理を書く

3 : .then(json => {...})

ここでやっと JSON データが使えるようになります。

例えばこんなデータが返ってきているとします

{
  "todos": [
    {"title": "ご飯をつくる"},
    {"title": "部屋の掃除をする"}
  ]
}

4 : map()<li>タグの配列を作る

const html = json.todos.map(todo => `
  <li>${todo.title}</li>
`).join('');
  • .map() … 配列の中身を変換して新しい配列を作る
  • テンプレートリテラル(` `)で <li>タイトル</li>
  • .join('') … 配列 → ひとつの文字列に結合

結果例

"<li>ご飯をつくる</li><li>部屋の掃除をする</li>"

5 : innerHTML で表示

list.innerHTML = html;

<ul id="list"> などの中に、作った <li> 群をINします!

これで画面にTodoが表示される!

処理全体のイメージ図

API(データの倉庫)
     |
     | fetch!
     v
{ todos: [...データ...] }
     |
     | JSONに変換
     v
mapで<li>に加工 → joinで1つの文字列に
     |
     v
innerHTMLでHTMLに挿入!

まとめ

技術要素 役割
fetch APIと通信
then 非同期処理のつなぎ
json() JSON形式へ変換
map 配列を変換
join 配列→文字列
innerHTML 画面に描画

おまけ:async/await版

async function fetchTodoData() {
  const res = await fetch('/serv/api/todo');
  const json = await res.json();
  const html = json.todos.map(todo => `
    <li>${todo.title}</li>
  `).join('');
  list.innerHTML = html;
}

個人的にはこっちの方がやってることが分かりやすくて好きだったりします。
好みで使い分けてみてください!

10
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
10
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?