Last active
December 4, 2022 21:45
-
-
Save YuriFontella/367282f5a2fc6fcdbcf77de414286d6a to your computer and use it in GitHub Desktop.
composable axios vue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Author
YuriFontella
commented
Dec 4, 2022
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