Incorporating a Vue plugin within a different Vue plugin

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.

Answer №1

After seeking guidance from the maintainer on Github, I was able to successfully solve the issue :-)

I modified my code so that a notification would only appear when I pressed a button after making another call. I realized that the initial call was happening in the created lifecycle hook of the root element, where the notification element did not exist yet. To resolve this, I moved the function call to the mounted lifecycle hook, and now everything is functioning perfectly.

https://github.com/euvl/vue-notification/issues/92

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display in Google Chrome without any dialogues

Hello friends, I am currently working on adding a print button to my website. I am testing it in Chrome and would like the page to be printed directly without showing any dialog boxes. However, I am facing some difficulties with this process. If anyone has ...

Hiding the modal once the data has been successfully transmitted to the database

I am facing a challenge in my app where I need to close the modal after sending data to the database, but no matter what I try, I cannot seem to achieve it. Can anyone provide some guidance or assistance with this? :) <div class="container-fluid"&g ...

Trigger AJAX request upon selecting a value from the dropdown menu

I am in the process of creating a basic dropdown menu that is only visible to users on mobile devices when they visit our website. The main objective is to allow users to select a value and then have that value sent via AJAX. For desktop devices, I have s ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Utilizing Angular JavaScript for detecting and setting up JDK installations

I am working on an application that requires the installation of Java JDK. Therefore, I need to develop a detection function for JDK in the system. If it is not found, I plan to install it using a setup provided by me and also set it in the system variabl ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

I must modify the initial statement to appear in bold from the paragraph with the use of JavaScript and CSS

Mr. XYZ and Mrs. ABC are known for their integrity. They own a stylish car. In the next paragraph, I would like to emphasize the first sentence by making it bold, We admire our exceptional leader J.K.L. He shows great potential. In this section, I wan ...

I received no response when I checked my Discord messages

I'm currently working on creating a bot that will send a daily morning message at 9 o'clock with a customizable reaction. Right now, it's successfully sending the message on Discord but there seems to be an issue with the reaction part. Can ...

React does not play well with Bootstrap's JavaScript and may cause it to not function or load properly

Initially, I set up a simple react application by running the command: npx create-react-app appnamehere Following that, I proceeded to install Bootstrap (trying both versions 4 and 5) with the command: npm install bootstrap After this, I included them in ...

I encountered an issue with route handlers in Next.js version 13.2. Sadly, they are not

I am trying to implement an API on my website with the endpoint /api/popular-movie. Here is an overview of my file structure: https://i.stack.imgur.com/e8Pf8.png Additionally, this is my route.ts code: import { NextResponse } from "next/server"; ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

What is causing this issue with the ajax call not functioning correctly?

$(document).ready(function(){ $('.clickthetext').click(function(){ $.post("submit.php", $("#formbox").serialize(), function(response) { $('#content').html(response); }); return false; }); ...

Verifying the activation status of a button within a Chrome extension

I have been working on a chrome plugin that continuously checks the status of a button to see if it is enabled. If it is, the plugin clicks on the button. I initially used an infinite for loop for this task, but realized that it was causing the browser to ...

Send a GET request to the API with an incremented value in the last parameter

Currently, I'm facing an issue with accessing data using pagination and lazy loading. The pagination system works fine for the first request, but the last parameter increment at the end of the page is not functioning as expected. For instance, when I ...

What is the best way to guide a user to a specific page based on the choice they made after submitting a form?

My form includes a list of 6 options where users can only select one. After submitting the form, I want to redirect them to a specific page based on their selection. For example, I have the following 3 options: Facebook Youtube Twitter If a user selects ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...

What steps can be taken to fix the issue of 'this is not defined' when trying to extend EventEmitter?

The code snippet below is encountering an error: var EventEmitter = require('events'); class Foo extends EventEmitter{ constructor(){ this.name = 'foo'; } print(){ this.name = 'hello'; co ...

Tips for placing order import styles css module as the first line in eslint-plugin-import configuration

I'm currently setting up ESLint for my project, using `eslint-plugin-import` to organize module import order. However, I have a specific case with a style CSS module that I want to place at the beginning of the import list. How can I configure ESLint ...

The event listener activates multiple times on HTML pages that are dynamically loaded with AJAX

Javascript utility function: // This event listener is set using the on method to account for dynamic HTML $(document).on('click', '#next_campaign', function() { console.log('hello'); }); Website layout: <script src=&q ...

What is the process by which React loads and runs JSX content?

What is the method used to identify and handle JSX code? <script src="src/main.js" type="text/babel"></script> ...