How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations are performed and I wish to display a toast notification when necessary. While I can easily achieve this using this.$ionic.toastController.create() within the vue instance, the absence of a vue instance in the external file is causing difficulties for me to import the ToastController and make it work.

Could someone provide guidance on how to overcome this obstacle?

I have explored various options and searched extensively online for solutions. Due to the fact that Ionic 4 with vue.js is still in alpha stage, support is limited at the moment. I have also experimented with the @modus/ionic-vue instance, which seems to function better than the original Ionic version currently.

The relevant code snippet is executed during a this.$store.dispatch(RESERVATION_REQUEST) call as shown below:

import { ToastController } from '@modus/ionic-vue'
import axios from 'axios'

const state = {
    status: '',
    classes: {},
}

const getters = {
    //
}

const actions = {
    [RESERVATION_REQUEST]: ({ commit, dispatch }, data) => {
        return new Promise(( resolve, reject ) => {
            axios({ url: 'reservation/create', data: { lesson: data.lesson, date: data.date, team: data.team }, method: 'POST' })
                .then(response => {
                    ToastController.create({
                        duration: 2000,
                        header: 'Confirmation',
                        message: 'Success',
                        position: 'top',
                        showCloseButton: true,
                        closeButtonText: 'Ok',
                    }).then(toast => toast.present());
                    resolve(response)
                })
                .catch(error => {
                    ToastController.create({
                        duration: 2000,
                        header: 'failed',
                        message: error.toString(),
                        position: 'top',
                        showCloseButton: true,
                        closeButtonText: 'Ok',
                    }).then(toast => toast.present());
                    reject(error)
                });
        });
    },
}

const mutations = {
    //
}

export default {
    state,
    getters,
    actions,
    mutations,
}

To invoke the above code, use the following method:

toggleReservation(lesson, date) {
    const team = this.$store.getters.getCurrentId;
    this.$store.dispatch(RESERVATION_REQUEST, { lesson, date, team });
}

I would greatly appreciate any assistance with this issue as I have been searching for a solution for several days now and although I feel like I am making progress, I have yet to find a definitive resolution.

Answer №1

To execute this, you can directly call the $store.dispatch function in your Vue instance.

store:

const actions = {
    [RESERVATION_REQUEST]: ({ commit, dispatch }, data) => {
        return new Promise(( resolve, reject ) => {
            axios({ url: 'reservation/create', data: { lesson: data.lesson, date: data.date, team: data.team }, method: 'POST' })
                .then(response => {
                    resolve(response)
                })
                .catch(error => {
                    reject(error)
                });
        });
    },
}

Vue file:

toggleReservation(lesson, date) {
    const team = this.$store.getters.getCurrentId;
    this.$store.dispatch(RESERVATION_REQUEST, { lesson, date, team })
            .then(response => {
                this.$ionic.toastController.create({
                        duration: 2000,
                        header: 'Confirmation',
                        message: 'Success',
                        position: 'top',
                        showCloseButton: true,
                        closeButtonText: 'Ok',
                    }).then(toast => toast.present());
            })
            .catch(error => {
                 this.$ionic.toastController.create({
                        duration: 2000,
                        header: 'failed',
                        message: error.toString(),
                        position: 'top',
                        showCloseButton: true,
                        closeButtonText: 'Ok',
                    }).then(toast => toast.present());
            });

}

PS: The axios function returns a promise, so you can simply return it in the store if needed.

const actions = {
    [RESERVATION_REQUEST]: ({ commit, dispatch }, data) => {
        return axios({ url: 'reservation/create', data: { lesson: data.lesson, date: data.date, team: data.team }, method: 'POST' })
    },
}

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

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

Looping through an array in Vue using v-for and checking for a specific key-value pair

As I dive into my first Vue app, I've encountered a minor setback. Here's my query: How can I iterate through a list of dictionaries in Vue, specifically looping through one dictionary only if it contains a certain value for a given key? Provi ...

Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLE ...

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

Ways to expedite the process of retrieving data for a JavaScript array

Looking to acquire the creation date of 20000 files and save it in an array. The total time taken is 35 minutes, which seems quite lengthy. (Image Processing Time) Is there a method to generate the array with a quicker processing time? Are there any i ...

top margin is functioning properly in Internet Explorer, but not in Google Chrome

margin-top is behaving differently in IE compared to Google Chrome. Two menus are supposed to be displayed one above the other in my design. The issue lies in the line margin-top:30%; within .anothermenu ul. In Chrome, the second menu appears above the f ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

"Updating data in Vue 3 does not trigger a re-render of the HTML

I am just getting started with Vue and I have a basic vue3 script set up using cdn instead of npm. index.html <div id="app"> <h2>{{ title }}</h2> <ul> <li v-for="item in items">{{ item }}</li> ...

Is it possible to identify a click that is being held without any movement?

Check out the code snippet below: doc.on('mousedown', '.qandacontent', function() { timeout_id = setTimeout(menu_toggle.bind(this), 1000); }).bind('mouseup mouseleave', function() { clearTimeout(timeout_id); }); If y ...

WebSocket - "Port is already being utilized"

I implemented the files provided in this article: into my codeigniter project, but I keep encountering an error: Message: socket_bind() [function.socket-bind]: unable to bind address [48]: Address already in use The JS section shows me: Connecting... C ...

ag-grid Server Side pagination function to enable independent setting of last row

Currently, I am utilizing ag-grid, Angular 7, and implementing a server-side datasource with pagination. In my API setup, I initiate two requests: the first request provides the total number of items in the table, while the second fetches the data for the ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

CoffeeScript is failing to run the code

I'm attempting to use a click function to alter the CSS code and then run a function. Here is my current code: ready: -> $("#titleDD").click -> $("#titleDD").css('text-decoration', 'underline'); $("#catDD").css( ...

Creating an array with user-selected objects in IONIC 3

I've been attempting to separate the selected array provided by the user, but unfortunately, I'm having trouble isolating the individual elements. They are all just jumbled together. My goal is to organize it in a format similar to the image lin ...

Is it possible to retrieve text from various iframes using the rangy library?

Here's a question that follows up on a problem I've been having with grabbing selected text from iframes using rangy. The code works well for the first iframe, but when I try to grab elements from multiple iframes using the same button, it doesn& ...

Steps for triggering the material-ui menu to appear on hover of a button

I attempted to implement the following code without success. I was able to achieve it using plain CSS, but I need to utilize the makeStyles function provided by material-ui. My goal is to display a drop-down list of items when a user hovers over the butto ...

Incorporate numerous style classes into an object using React Material-UI

I am facing an issue with my JSX code: <span className="btn-pause btn"><i class="fa fa-pause"></i></span> I would like to change the color of this button. Here is what I have tried: const styles = { btncolor ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...