Skip to content

Instantly share code, notes, and snippets.

@YuriFontella
Last active December 4, 2022 21:45
Show Gist options
  • Save YuriFontella/367282f5a2fc6fcdbcf77de414286d6a to your computer and use it in GitHub Desktop.
Save YuriFontella/367282f5a2fc6fcdbcf77de414286d6a to your computer and use it in GitHub Desktop.
composable axios vue
import { inject, reactive, toRefs } from 'vue'
import { Cookies, Notify } from 'quasar'
export function useHttp() {
const state = reactive({
loading: false, data: null
})
const api = inject('api')
api.interceptors.request.use(function (config) {
const session = Cookies.get('token')
if (session) {
config.headers['x-access-token'] = session
}
return config
})
const execute = async (options) => {
try {
state.loading = true
const response = await api(options)
if (response.status === 200) {
state.data = response.data
}
} catch (e) {
if (e.response) {
Notify.create(e.response.data.message)
}
else if (e.request.status === 0) {
Notify.create('Não foi possível enviar a solicitação')
}
else Notify.create(e.message)
}
finally {
state.loading = false
}
}
return {
...toRefs(state), execute
}
}
@YuriFontella
Copy link
Author

import { boot } from 'quasar/wrappers'
import axios from 'axios'
import { Cookies } from 'quasar'

const api = axios.create({ baseURL: process.env.API })

export default boot(({ app }) => {

  api.interceptors.response.use(function (response) {

    return response

  }, function (error) {

    Cookies.remove('token')

    return Promise.reject(error)
  })

  app.provide('api', api)
})

@YuriFontella
Copy link
Author

import { useHttp } from 'src/composable/http'
const { data, loading, execute } = useHttp()

onBeforeMount(async () => {
  await execute({ url: 'players', method: 'GET' })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment