Leveraging TypeScript global variables in SharePoint operations

In TypeScript and Angular, I've developed a function called getTasks() that should run when a modal is closed. Here's the code for the function:

getTasks() {
 this.http.get(`https://example.com/_api/web/lists/getbytitle('Tasks')/items`).subscribe(data => {
  console.log(data['value'])
  this.tasks = data['value']
 })
}

I'm able to create my modal successfully using the following:

newTask() {
  var options = {
    url: `https://example.com/divisions/dev/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
    dialogReturnValueCallback: Function['createDelegate'](null, this.newTaskClosed)
  }
  window.parent['SP'].UI.ModalDialog.showModalDialog(options);
}

This is the callback function that logs when the modal is closed:

newTaskClosed(result, value) {
  console.log(result, value)
  this.getTasks(); // 'this' appears as null here
}

But executing this code results in the error:

Uncaught TypeError: Cannot read property 'getTasks' of null

Any ideas on how to fix this issue?

Answer №1

Testing in my environment did not result in any errors.

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

Here is a demo of the test:

private newTask= (): void =>{
    var options = {
      url: this.props.context.pageContext.web.absoluteUrl+`/lists/ParentA/NewForm.aspx`,
      dialogReturnValueCallback: Function['createDelegate'](null, this.newTaskClosed)
    }    
    window.parent['SP'].UI.ModalDialog.showModalDialog(options);
  }
  
  private newTaskClosed= (result, value): void => {
    console.log(result, value);    
    this.getTasks(); // 'this' might be null here
  }
  
  private getTasks= (): void => {
    alert('getTasks function')
   }

To call the dialog in the Render function:

return (     
      <div >  
        <Button text="NewTask" onClick={this.newTask} />

Answer №2

My solution originated from utilizing this posted answer as a reference point. By implementing an arrow function for the dialogReturnValueCallback attribute, I was able to preserve the proper context of this. Additionally, I achieved success by accessing this.getTasks() through a variable that binds this.

The modification made to the options object was:

let options = {
  url: `https://portal.oldnational.com/divisions/it/iDemand/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
  dialogReturnValueCallback: () => this.getTasks()
}

Alternatively, I also had success with:

let boundFunction = (function() {
  this.getTasks();
}).bind(this);

let options = {
  url: `https://portal.oldnational.com/divisions/it/iDemand/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
  dialogReturnValueCallback: boundFunction
}

This approach proved effective in my scenario.

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

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Simulating NestJS Injected Connection Imported from Another Module

Today, I've been facing this persistent error: Encountering an issue with the ClubsService where Nest is unable to resolve dependencies (specifically DatabaseConnection). The error message prompts me to ensure that the argument DatabaseConnection at i ...

What are the guidelines for utilizing square brackets [ ] in directives like @Inputs?

I'm feeling a bit lost. Check out this straightforward directive: @Directive({ selector: '[myDirective]' }) export class MyDirective { private textContent: string; private isEnabled: boolean; @Input() myD ...

Identify and handle errors effectively using TypeScript

I have a question regarding my Express server setup. Here is the code snippet: import express from "express"; import helmet from "helmet"; import cors from "cors"; const app = express(); app.use(helmet()); app.use(cors()); a ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

The FullCalendar does not appear as expected on Angular version 16

https://i.stack.imgur.com/DTAKr.pngI followed the steps to install FullCalendar in my Ionic 6 Angular 16 app as outlined on https://fullcalendar.io/docs/angular. However, nothing is showing up in the browser (chrome). The Inspector tool shows that the Ful ...

Steps for setting up the 'node_modules' folder in an older Angular project using the 'npm install' command

Currently, I am in the process of transferring our project code from our repository to a new laptop. The project was initially developed on Angular 5 last year. However, the new laptop is equipped with the latest versions of Angular CLI, NodeJS, and NPM to ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

The animation fails to retain its final state and reverts back to its initial state

Currently, I am diving into learning Angular 6 and encountered a small issue. Following this tutorial: Upon clicking the button, the animation executes as intended. However, after the fade-out effect, the text reappears abruptly. Any insights on why it re ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

How to Place a Button Halfway Out of an Angular 5 Material Dialog

Is there a way to place a close button on the top right corner of a dialog box, partially inside and outside the dialog like shown in this image: I attempted using absolute positioning to achieve this, but that solution is not ideal. I want to position t ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Warning: The attribute 'EyeDropper' is not recognized within the context of 'Window & typeof globalThis'

Attempting to utilize "window.EyeDropper" in a project that combines vue2 and TypeScript. When writing the following code: console.log(window.EyeDropper); An error message is generated by my Vetur plugin: Property 'EyeDropper' does not exist on ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

Guide to making a Typescript interface by combining elements from two separate interfaces without utilizing inheritance

Programming Language: Typescript I am looking to combine the properties of two interfaces as the value of an indexable-type within a third interface. Interface 1: export interface Employee { id: string name: string } Interface 2: export interfa ...

Error TS2393 in Typescript: Multiple function declarations found within a Node/Express application

In my TypeScript node + express application, I have implemented a function in some API routes that looks like this: function cleanReqBody(req) { req.body.createdBy = req.user; req.body.modifiedBy = req.user; req.body.modified = new Date(); } Howeve ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...