A
A
Analka2021-11-29 15:35:10
Vue.js
Analka, 2021-11-29 15:35:10

How to create your own useFetch?

Hello! I use vue3 + vite

How in Vue you can create your own useFetch so that you can insert both fetch and axios

in NuxtJs it's implemented like this

import { VueConstructor } from 'vue'

declare type ComponentInstance = InstanceType<VueConstructor>

interface Fetch {
  (context: ComponentInstance): void | Promise<void>
}

    declare const useFetch: (callback: Fetch) => {
      fetch: () => void
      fetchState: {
        error: Error | null
        pending: boolean
        timestamp: number
      }
      $fetch: () => void
      $fetchState: {
        error: Error | null
        pending: boolean
        timestamp: number
      }
    }

using

useFetch(async () => {
      await $axios.$get(`/api/v1/admin/tariffs`).then((response: any) => {
        tariffs.value = response.data
      })
    })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-11-29
@Aetae

useFetchused in nuxt to work coherently with state in SSR.
If you don't use SSR, you don't need it. And yes, as already noted, this hook has nothing to do with axios or fetch as such.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question