What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular.

Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates whether a transaction has Failed, is successful, or is in pending status. In case of a failed transaction, I want the user to receive a swal alert/notification like the one below:

swal({
       title:'Error!',
       text: 'Warning... Transaction failed!',
       type: 'error',
       confirmButtonText: 'Ok',
       confirmButtonColor: '#ff754f'
     });

My current code snippet looks like this:

../component.html

<div class="sign-btn text-center">
  <a class="btn btn-lg text-white">
    <span *ngIf="tab1TrxMessage">{{tab1TrxMessage}}</span>
    <span *ngIf="!tab1TrxMessage && tab1TrxStatus != 'Success'">Failed</span>
    <span *ngIf="transactionFailed()">Failed</span>
  </a>
</div>

Focusing on the transactionFailed() function...

../component.ts

public transactionFailed() {

    if(this.tab1TrxMessage == 'Failed: Cancelled by User' && this.tab1TrxStatus != 'Success') {

        console.log("You are in transactionFailed!")

        swal({
           title:'Error!',
           text: 'Warning... Transaction failed!',
           type: 'error',
           confirmButtonText: 'Ok',
           confirmButtonColor: '#ff754f'
         });

         return true;
    }

    return false;
}

After a failed transaction using the above code, the message You are in transactionFailed! appears multiple times in the browser console...

https://i.sstatic.net/Qs7Od.png

...and the swal alert with Warning... Transaction failed! keeps popping up repeatedly. This situation leads me to wonder if there's a better way to ensure that the swal alert displays only ONCE per failed transaction?

I would appreciate your suggestions and guidance.

Answer №1

Create a mechanism to ensure that your code runs only once, like a counter.

failedTransactionCntr = 0;
public transactionFailed() {

    if(this.tab1TrxMessage == 'Failed: Cancelled by User' && this.tab1TrxStatus != 'Success') {

        console.log("You are in transactionFailed!")
        if (this.failedTransactionCntr == 0) {
          swal({
           title:'Error!',
           text: 'Warning... Transaction failed!',
           type: 'error',
           confirmButtonText: 'Ok',
           confirmButtonColor: '#ff754f'
         });
         this.failedTransactionCntr ++;
        }
         return true;
    }

    return false;
}

Answer №2

When it comes to the way Angular detects changes, the transactionFailed() function is triggered during each change detection cycle due to your specified strategy and method. This is necessary because updating the DOM is a crucial aspect of change detection in Angular, requiring the invocation of transactionFailed() to determine the appropriate value for DOM updates.

To prevent multiple calls to transactionFailed(), consider changing the changeDetectionStrategy to onPush:

@Component({
 selector: 'your-component',
 templateUrl: './your.component.html',
 styleUrls: ['./your.component.css'],
 changeDetection: ChangeDetectionStrategy.OnPush // this line
})

export class YourComponent {

}

However, keep in mind that you may need to manually trigger change detection by calling the detectChanges() method:

constructor(private ref: ChangeDetectorRef) {
    this.ref.detach();
}

start() {
    this.fooVariable = 'This is a foo vaiable';
     this.ref.detectChanges();
}

For more information on Change detection strategies, refer to this article

Answer №3

If you want to ensure it is only valid once, consider using a flag variable. For instance:

let transactionFlag = false; 
public transactionFailed() {

    if(this.tab1TrxMessage == 'Failed: Cancelled by User' && this.tab1TrxStatus != 'Success' && !transactionFlag) { 

        console.log("You are in transactionFailed!")
        transactionFlag = true;
        swal({
           title:'Error!',
           text: 'Warning... Transaction failed!',
           type: 'error',
           confirmButtonText: 'Ok',
           confirmButtonColor: '#ff754f'
         });

         return true;
    }

    return false;
}

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

Utilizing JavaScript regex for patterns such as [x|y|z|xy|yz]

Looking for a regex solution: \[[^\[\]]*\]\s*[<>|<=|>=|=|>|<]\s*'?"?\w*'?"? This regex is designed to parse equations like: [household_roster_relationships_topersona_nameadditionalpersono] = ...

``Trouble with React Dropdown menu option selection"

I am encountering challenges with implementing a dropdown menu list for my react app. The issue at hand is that I have an API where one of the keys (key3) has values separated by commas that I wish to display in my dropdown list. The structure of the API ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...

Steps to reinitialize the error code after removal from the roster

Currently, I am working on creating a series of textboxes and dropdown menus using jQuery. So far, the add function is functioning smoothly without any glitches. However, my issue lies within the delete function. It works well when deleting sequentially, ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

Creating a interactive navigation bar with External JSON data in HTML and JavaScript

Is there a way to create a dynamic MenuBar by using an external JSON file? How can I write HTML code to fetch and display JSON data dynamically? What is the process for reading a JSON file? //JSON File = Menu.Json {"data": [{"id": "1", "text": "F ...

Error message: "Unable to POST image with Node/Express (React frontend) while attempting to upload

I am a beginner in Node.JS and currently working on developing a MERN movie ticket booking system. The front-end code snippet provided below showcases the function responsible for uploading an image for a specific movie: export const uploadMovieImage = ( ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Warning: HTML input values are being cleared when added

I've been working on some code that adds an input field when a button is clicked. When the limit reaches 5 (counter), it displays a bootstrap warning. The issue I'm facing is that after hitting "add field" more than 5 times, the values in the fie ...

Ways to modify the values of a Bootstrap Dropdown using a unique identifier

Here is an example of a typical Bootstrap Dropdown: <div class="btn-group"> <button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class ...

By default, apply the active class to the initial element in the list and update the active class upon clicking in Next.js

As a newcomer to React, I am struggling with setting the active class in my CSS file. I have two classes, btn and active. My goal is to assign the active class to the first button by default and then switch it to the currently clicked button when interacti ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

NextJs's React-Quill is unable to effectively highlight syntax using the highlightJS library

I have been working on a NextJs application (blog) that utilizes react-quill as a rich text-editor. As part of my setup, I am making use of the Next custom 'app' feature, where my UserProvider component wraps everything to provide global access t ...

Angular 5 Directive for Structuring Content

I'm currently in the process of developing a versatile search box component, with the following setup: search.component.html <div class="search-box-container"> <fa-icon class="search-icon" [icon]="faSearch"></fa-icon> <input ...

Trouble with executing AJAX for API call

My current project is built on CI3 and I have created an API that belongs to a different domain than the application itself. $.ajax({ url: "http://www.example.com/restapi/index.php/api/user", type: "GET", data: {"user_id": user_id} ...