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

Tips on utilizing innerHTML or innerText to add content to the Evernote editor, a rich text editor

A method authored by Jayant was employed in this particular post how-to-insert-text-into-the-textarea-at-the-current-cursor-position to perform an insertion into the Evernote editor. The Evernote editor being a rich text editor, altering from el.value to ...

Validation does not occur when the submit button has an ng-click event attached to it

This is the form I created: <form action="" ng-controller="forgotCtrl as forgot" name="forgotForm"> <div class="form-group row"> <label for="email" class="col-sm-2 form-control-label">Email address</label> ...

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

What is the way to utilize a scope variable within an ng-repeat filter?

I'm feeling a bit lost trying to navigate through this task with AngularJS. As a newbie to the framework, I'm struggling to find out how to achieve what I need. I have a group of users that I am looping through by using ng-repeat, but I can' ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Migration processes encountering delays due to running nodes

When running migrations in Node, I am encountering a timeout error. The specific error message is: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. Here is the ...

Learn how to use Vue.js with vue-phone-number-input package to programmatically set the country code and phone number in your application

Within my Laravel and Vue.js SPA (Single Page Application), I am utilizing several packages including BootstrapVue, vue-phone-number-input package, and VeeValidate. Once the user enters the country code and phone number, I can retrieve them independently ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

Tips on aligning a v-btn alongside v-expansion-panels on the same row

Struggling with aligning my layout. Trying to get a single set of v-expansion-panels and a v-btn in the same row, both visually centered within a card. I managed to almost achieve it in this codepen: https://codepen.io/anzuj/pen/PoPPbdw with the following ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Extract specific data points from external API responses on a webpage crafted in HTML

I require assistance on how to extract individual values from an HTML page. I received a response from the PAYU payment gateway team in HTML format, but I need to retrieve specific attribute values related to the transaction details. Below is the response ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Change the content of a selectbox dynamically with the help of jQuery and AJAX

Currently, I am exploring the best approach for a specific challenge: I have various categories, subcategories, sub-subcategories, and so on, that I need to display in separate select boxes. For instance, initially, the options may look like this: <sel ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

Issue with Selenium webdriver functionality in Electron development build

I've been working on an Electron project where I render an HTML page with a button that, when clicked, triggers a Node.js script (via IPC) using Selenium to scrape webpages. Here is the structure of my project: -app/ --index.html --ma ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

JavaScript sticky navigation bar - error displayed in console

Hey there, I'm having an issue with my Sticky-menu. I've been trying to troubleshoot it but keep getting these console error messages: 1. Cannot read property 'offsetTop' of null at HTMLDocument. 2. Cannot read property 'class ...