Retrieving a global variable within a nested function

I am encountering a scope issue with my nested function while trying to pass two global variables. I need some help as I keep getting this error when running the code:

Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'user')
TypeError: Cannot read properties of undefined (reading 'user')
mark_paid(id: any) {
    Swal.fire ({
      title: 'Are you sure?',
      text: "You must ensure that you have sent the money first before clicking this button. Providing false information or coinlocking will cause your account to be banned",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#7367F0',
      cancelButtonColor: '#E42728',
      confirmButtonText: 'Yes, ive sent it',
      customClass: {
        confirmButton: 'btn btn-primary',
        cancelButton: 'btn btn-danger ml-1'
      }
    }).then(function(result){
      if (result.value) {

     

        const headerDict = {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          token:this.user.token,//I am attempting to access this global variable
          username: this.token.username
        }

        const requestOptions = {
          headers: new Headers(headerDict),
        };

        return fetch('https://some.endponint.com/markPaid/'+id,requestOptions)
          .then(function (response) {
            console.log(response);
            if (!response.ok) {

              throw new Error(response.statusText);
            }else{

              Swal.fire({
                title: 'Trade Marked as Paid',
                text: 'The seller will check on your payment and send the BTC shortly',
                icon: 'success',
                customClass: {
                  confirmButton: 'btn btn-success'
                }
              });
             location.reload();
            }
            return response.json();
          })
          .catch(function (error) {
            Swal.fire({
              title: 'Ops',
              text: 'An error happened please try again',
              icon: 'error',
              customClass: {
                confirmButton: 'btn btn-success'
              }
            });
          });

      }
    });
  }

Answer №1

If user is defined as a global variable at the beginning of the function, store the current reference scope:

mark_paid(id: any) {
    let user = user;
    Swal.fire ({

Answer №2

Ensure that the 'this.user' variable contains a token value and is not null. Verify the assigned value of 'this.user'. The error is likely caused by 'this.user' lacking a proper value.

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

Encountered a problem while installing an npm package for Angular 2

I seem to be encountering an error when trying to run the npm install command in the command prompt behind my corporate proxy firewall. Previously, I was able to edit the npm file with the proxy settings, but now I receive this error no matter what npm com ...

Every time I attempt to create a new ionic project using angular through the console, I encounter the error message: "npm ERR! Cannot read properties of undefined (reading 'isServer')"

Having an issue with npm where it is giving the error "Cannot read properties of undefined (reading 'isServer')." I have updated npm to the latest version and tried force-clearing the cache, but the issue persists. Can anyone provide assistance? ...

Encountering a TypeError while attempting to retrieve an instance of AsyncLocalStorage

In order to access the instance of AsyncLocalStorage globally across different modules in my Express application, I have implemented a Singleton class to hold the instance of ALS. However, I am wondering if there might be a more efficient way to achieve th ...

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...

Utilizing TypeScript for various return types with the same parameters

Exploring TypeScript Signatures In an effort to embrace TypeScript fully, I am implementing strongly typed signatures in my Components and Services, including custom validation functions for angular2 forms. I have discovered that while function overloadi ...

Error: No injection provider found for function(){}!

After countless hours of setting up a custom AOT in Angular 7 project without CLI and debugging, I have encountered the following error: Uncaught Error: StaticInjectorError(Platform: core)[function(){}]: NullInjectorError: No provider for function(){}! ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Struggling to locate root directory post-Angular 13 upgrade in Jest

After updating my project to Angular 13, I realized that Jest required some adjustments as well. Now, any mention of 'src' cannot be resolved properly. For instance: Cannot find module 'src/app/app.component/app.component.test' from & ...

What is preventing me from utilizing Omit with AsyncProps in react-select?

My current challenge involves wrapping a custom component called SelectSearchResult around the AsyncSelect component from the library react-select. I want most of the props for my custom component to be similar to those of AsyncSelect, but with some except ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

How can I retrieve distance data from the Google Maps API within an Angular service?

I am currently working on implementing the JavaScript version of the Google Maps API in order to resolve a CORS issue that I encountered with the regular API. Specifically, I am looking to calculate the distance and time between two destinations. How can I ...

Exploring Angular RxJS: the art of filtering Observable arrays

Is there a way to effectively filter an array Observable in Angular? I am working with an observable Array: announcementList$: Observable<Announcement[]> = this.announcementService.getAnnouncement(0,0).pipe(filter(Boolean),shareReplay(), map(({data} ...

Encountering compilation errors with Angular project following installation of a package

I recently installed the LocalStorage Package and encountered the following message: npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

The property 'owlDateTimeTrigger' cannot be bound to 'span' as it is not recognized

I have integrated the OwlDateTimeModule into my smart-table-datepicker component. Although I imported it in my smart-table-datepicker.module file, I am still encountering errors. What could be causing this issue? smart-table-datepicker.module.ts import { ...

The id attribute is missing in ionic 2's innerHTML

I've got a script that looks like this... This is the TypeScript part: export class sampleClass { content: any; constructor(public navCtrl: NavController, public navParams: NavParams) { this.content = [ {title: "Title 1", body:"<div id ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: https://i.sstatic.net/70W6Q ...

Remove the parent component's tag

In my HTML template, I have included a <table> element and inserted a custom-component within one of its rows, as shown below: <table> <thead> .... </thead> <tbody> <tr> <CustomComponent>< ...

Tips for invoking a function on a react-bootstrap-table component using TypeScript

One issue I'm encountering is trying to cast the "any" bootstrapTableRef to react-bootstrap-table, setting up the ref correctly, or importing it incorrectly. I am struggling to access the method of the imported table. While I found a solution using th ...