I am revamping my website by incorporating Vue in the frontend and Django Rest Framework in the backend. To streamline the authentication/headers/error handling for all AJAX calls, I decided to centralize this logic within a shared file. Thus, I created a fetchPlugin.js
that manages these aspects and integrated it into my Vue instance under $fetch
.
For displaying notifications, I have implemented vue-notification
, allowing me to easily show notifications using $notify
. However, I encountered an issue within my $fetch
plugin. While the calls within callback functions of fetches do work when utilizing Vue.prototype.$notify
, they do not directly inside the function itself. See the commented code below:
let fetchPlugin = {}
fetchPlugin.install = function(Vue, options){
Vue.prototype.$fetch = {
get(url, processingFunction, show_loading=false, extra_options={}){
if(show_loading){
// This call does not work
Vue.prototype.$notify({
group: 'loading',
title: 'Loading...',
type: 'success'
})
}
let default_options = {
credentials: 'same-origin',
}
options = Object.assign(default_options, extra_options)
fetch(url, options)
.then(function(response){
if(show_loading){
// This call works
Vue.prototype.$notify({
group: 'loading',
clean: true
})
}
if(!response.ok){ throw response }
return response.json()
})
.then(processingFunction)
.catch(err => {
console.log(err)
// This call also works
Vue.prototype.$notify({
group: 'fetch',
title: 'An error occurred',
type: 'error'
})
})
}
}
}
export default fetchPlugin
In my main.js
, I imported and utilized vue-notification
before my fetchPlugin
. Consequently, I assumed I would have access to the $notify
function added by vue-notification
. Since there is no Vue instance available during setup time:
Vue.use(Notification)
Vue.use(fetchPlugin)
However, it seems that accessing $notify
works within the .then
functions but not outside of them. How can I ensure the loading notification functions as expected?
Update: After confirming with console.log(Vue.prototype)
that $notify
is present both in the fetch callback function and at the start of my plugin's get
function, it should not be throwing any exceptions. The question remains why no notification pops up even though the function is being called correctly without any exceptions occurring.