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?

More than 1 year has passed since last update.

Nuxt3 / Vue3 – util で Fetch の処理を共通化する

Posted at

内容

  • utils に共通処理を置いて Vue ファイルから呼び出す
  • fetch の結果として 呼び出し側の data を書き換えるには then の中で処理する必要があるので、 共通関数の引数として data を渡してしまう

呼び出し側

Foo.vue

<script lang="ts" setup>

const errors = ref([])
const result = ref([])

fetchFoo({result: result, errors: errors})

</script>

Util

utils/fetchFoo.ts

export const fetchFoo = ({result: result, errors: errors}) => {
  let httpStatus = 0

  const fetchURL = new URL(`/path/to/api`)

  const fetched = fetch(fetchURL, {
    method: "GET",
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then((response) => {
      httpStatus = response.status
      return response.json()
    })
    .then((response_json) => {
      if (httpStatus == 200) {
        result.value = response_json["result"]
      } else if (response_json['errors']) {
        errors.value = response_json['errors']
      } else {
        errors.value = ["データ取得でエラーが発生しました"]
      }
    })
    .catch((_error) => errors.value = ["接続でエラーが発生しました"]);
}

チャットメンバー募集

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

Twitter

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?