Nuxt3のuseFetch()のパラメータにcomputedやrefの値を用いると、それらが変更されるたびにリクエストが行われる

useFetch automatic request after first request · Issue #15741 · nuxt/nuxt より

動作検証サンプル ( https://github.com/nuxt/nuxt/issues/15741#issuecomment-1397417760 ) より

<script setup>
const formData = reactive({
  username: "",
  password: "",
  confirmPassword: null,
});

const handleSubmit = async () => {
  console.log("Running handleSubmit...");
  const response = await useFetch("/api/register", {
    method: "POST",
    body: formData,
  });
};
</script>

<template>
  <div>
    <h2>Register</h2>
    <form @submit.prevent="handleSubmit">
      <div>
        <label>Username</label>
        <input v-model="formData.username" type="text" />
      </div>
      :
      :
      :
      :
      <div class="pt-2">
        <button type="submit"> Register </button>
      </div>
    </form>
  </div>
</template>
  1. 各項目を入力する
  2. Registerボタンを押すとhandleSubmit()が実行され、/api/registerへPOSTリクエストが発行される
  3. input要素の内容を書き換えると、書き換えるたびに2.のPOSTリクエストが発生する。送信されるパラメータは書き換えた最新の値

リクエストサンプル

これは、Nuxt3のドキュメントに書かれている、正常な動作である。

useFetch · Nuxt Composables

All fetch options can be given a computed or ref value. These will be watched and new requests made automatically with any new values if they are updated.

すべてのfetchオプションは、computedまたはrefを与えることができます。これらは監視され、新しい値に更新された場合は自動的に新しいリクエストが行われます。

これを回避したいときは、

  1. パラメータにref/reativeをそのまま用いるのをやめる

      const response = await useFetch("/api/register", {
        method: "POST",
        body: JSON.stringify(formData),
      });
      
      または
      
      const response = await useFetch("/api/register", {
        method: "POST",
        body: {...formData},
      });
    
      または
      
      const response = await useFetch("/api/register", {
        method: "POST",
        body: formData.value,
      });
    
  2. useFetchの代わりに$fetchを用いる

      const response = await $fetch("/api/register", {
        method: "POST",
        body: formData,
      });