Display an alert message only the first time a checkbox is checked

I have a checkbox that, when checked, triggers an alert asking if the user is sure. Upon agreement, all exercises are marked as done.

The problem: I use local storage to save an item called didAllExercises. When reopening the app, if this item is true, the checkbox is set to true. However, there is an (onChange) event on the checkbox that displays an alert when checked. This causes the alert to appear every time the app is reopened, even if the didAllExercises item is true.

Here is the checkbox:

<ion-checkbox checked="false" [(ngModel)]="cheatCheckbox" (ionChange)="cheatButton(cheatCheckbox)"></ion-checkbox>

This is my cheatButton() function:

cheatButton(cheatCheckbox: boolean){

    if(cheatCheckbox){
      localForage.setItem("showAlert", true);
      console.log('ccTrue', cheatCheckbox);

      //DO NOT SHOW ALERT WHEN ALL EXERCISES ARE DONE AND YOU REOPEN THE APP TO NAVIGATE

      setTimeout(() => {        
        localForage.getItem("showAlert", (err, value) => {
          if(value){
            this.showAlert = value;

            console.log('!notRun', value);
          }
        })
      },400)

      setTimeout(() => { 
              let alert = this.alertCtrl.create({
                  title: 'Complete all exercises',
                  message: 'Are you sure you have completed all exercises?',
                  buttons: [
                    {
                      text: 'No',
                      role: 'cancel',
                      handler: () => {
                        console.log('Cancel clicked');
                        this.cheatCheckbox = false;
                      }
                    },
                    {
                      text: 'Yes, I am sure!',
                      handler: () => {
                        this.allExercisesDone = true;
                        localForage.setItem('didAllExercises', [true, this.data]);              
                      }
                    }
                  ]
                });

                alert.present();
      },400)
    }    
  }

And here I call the getItem method in the ionViewWillEnter:

 localForage.getItem('didAllExercises', (err, value) => {
    if(value){
      this.cheatCheckbox =  true;
     }
})

How can I resolve this issue so that the alert only appears once upon clicking it, and then subsequently opening the app with the checkbox set to true without triggering the same alert?

Answer №1

To resolve the issue, instead of utilizing ionViewWillEnter, it is suggested to call localForage.getItem within the constructor. If your problem persists, consider implementing a flag named checkBoxInitialized. Initialize this flag to true in the constructor and utilize it as shown below:

localForage.getItem('didAllExercises', (err, value) => {
    if(value){
      this.cheatCheckbox =  true;
     } else {
      this.cheatCheckbox =  false;
     }
    this.checkBoxInitialized = false;
})

Subsequently, adjust cheatButton as follows:

cheatButton(cheatCheckbox: boolean){

    if(cheatCheckbox && this.checkBoxInitialized){ 
    ...

    }else
       this.checkBoxInitialized = true;

Additionally, there seems to be redundancy in passing cheatCheckbox as a parameter to cheatButton. You may always access it using this.cheatCheckbox.

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

Typescript conditional types make room for the inclusion of null values

Consider this scenario involving conditional types: type MyType = 'Number' | 'String'; interface Test<T extends MyType> { bar: T extends 'Number' ? 25 : '25' } When attempting the following assignment: co ...

What properties are missing from Three.js Object3D - isMesh, Material, and Geometry?

Currently, I am working with three.js version r97 and Angular 7. While I can successfully run and serve the application locally, I encounter type errors when attempting to build for production. Error TS2339: Property 'isMesh' does not exist on ...

Leverage Springs with TypeScript

function createDefaultOrder(items: any[]): number[] { return items.map((_, index) => index); } type CustomHandler<T> = (index: number) => T; type CustomValues = { zIndex: number, y: number, scale: number, shadow: number, immediate: ...

Conditionally setting a property as optional in Typescript

Imagine a scenario where I have a type defined as interface Definition { [key: string]: { optional: boolean; } } Can we create a type ValueType<T extends Definition> that, given a certain definition like { foo: { optional: true } ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...

Implementing type inference for response.locals in Express with TypeScript

I need to define types for my response.locals in order to add data to the request-response cycle. This is what I attempted: // ./types/express/index.d.ts declare global { declare namespace Express { interface Response { locals: { ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

Which is better for narrowing object property types: using dot notation or object literal notation?

Is there a reason why type narrowing by assignment behaves differently based on whether we use dot notation or object literal notation? Below are two examples to illustrate this discrepancy. type MyObj = { x?: number | string } let obj1: MyObj = {} obj1.x ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Troubleshooting problems with building an Angular project containing Angular Slickgrid

After successfully migrating my project from Angular 13 to Angular 17 and updating angular-slickgrid from version 4.1.4 to 7.5.0, I am facing a build error that I cannot resolve. I have addressed all other errors except for one: When compiling with Angular ...

Use Angular's super.ngOnDestroy method for handling cleanup/unsubscribing

When it comes to unsubscribing / cleaning up from observables in Angular components (using ngOnDestroy), there are multiple options available. Which option should be considered the most preferable and why? Also, is it a good practice to include super.ngOnD ...

How to format decimals in Typescript/Angular with a pipe: comma or dot?

I've recently developed a custom pipe and I'm looking to enhance it by adding commas or periods to thousands values. For instance, 1000 should be displayed as either 1,000 or 1.000. Here is the code snippet for my custom pipe: import { Pipe, Pi ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Is it possible to utilize an @Input() in Angular with multiple types?

Is it possible for a parent component to pass an object in @Input to the child component that may not always be the same? For instance, can I use: @Input() obj: string | number; In my scenario, I have two different objects as potential inputs: @Input() ob ...

How can TypeScript be used to define an onClick event that can also be triggered by keyboard input?

In the React Typescript guide, it suggests typing a click event as follows: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#basic-prop-types-examples onClick(event: React.MouseEvent<HTMLButtonElement>): void; However, buttons ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...