LoginSignup
3
0

Nuxt3 の fetch / $fetch / useFetch の違い

Last updated at Posted at 2024-02-15

まとめ

  • useFetchは setup / middleware だけで使う
  • $fetch はユーザー行動に応じて利用する用途
  • fetch$fetch とは別物で、fetch はもう使わなくて良さそう

警告

setup / middleware 以外で useFetch を使った時に、console で以下が警告がされる

[nuxt] [useFetch] Component is already mounted, please use $fetch instead.
See https://nuxt.com/docs/getting-started/data-fetching

たとえば次のように、ボタンを押した時などに useFetch を使うと警告される

<script setup lang="ts">
function fetchTODO() {
  useFetch('https://jsonplaceholder.typicode.com/todos/1')
}
</script>

<template>
  <div>
    <button @click="fetchTODO">Fetch</button>
  </div>
</template>

ドキュメント

useFetch は setup や middleware で使うもののようだ

useFetch is the most straightforward way to handle data fetching in a component setup function.

$fetch は ユーザーのインタラクション(操作とか) に応じてリクエストするのに合っているっぽい

$fetch is great to make network requests based on user interaction.

$fetch とは何なのか

  • fetch$fetch は別物のようだ
  • $fetchofetch のエイリアスらしい

Nuxt includes the ofetch library, and is auto-imported as the $fetch alias globally across your application. It's what useFetch uses behind the scenes.

なおかつ今見返してみると fetch の例は Nuxt のドキュメントにはない気がした (前にあったのかどうかも分からない)

$fetch と fetch の違いを試してみる

$fetch の場合

$fetch は戻りの値をそのまま受け取れるので template で使いやすくなっている

<script setup lang="ts">
let data = ref()

async function fetchTODO() {
  data.value = await $fetch('https://jsonplaceholder.typicode.com/todos/1')
}
</script>

<template>
  <div>
    <button @click="fetchTODO">Fetch</button>
  </div>

  <div>
    {{ data }}
  </div>
</template>

fetch の場合

template でレスポンスの値を使うには、次のように then で処理する必要があったと思う
(書くのが大変)

<script setup lang="ts">
const result = ref()

async function fetchTODO() {
  await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => {
      return (result.value = res.json())
    })
    .then((jsonResponseData) => {
      result.value = jsonResponseData
    })
}
</script>

<template>
  <div>
    <button @click="fetchTODO">Fetch</button>
  </div>

  <div>
    {{ result }}
  </div>
</template>

では useFetch はどんな時に使ったら良いのか?

ユースケースはまだよく分かっていない。(自分が)

関連

Nuxt3 – useFetch / useAsyncData / fetch – リクエスト対象のURLやパラメータを変えて再リクエスト出来るのか?
https://github.com/YumaInaura/YumaInaura/issues/3525

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

プロフィール・経歴

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