Is my approach to CSV parsing correct if I am receiving the error "Unable to assign property 'processing' to undefined"?

In our database, we store words along with their categories. I have a new requirement to enable the word administrator to upload multiple words at once using a CSV file. Currently, our system only allows for single-word additions at a time. My solution was to call the existing function repeatedly for each word in the CSV file.

Below is the constructor and dependencies of my component:

export class AdminComponent implements OnInit {
  currentJustify = 'start';
  processing = false;
  error = false;
  errorAdd = false;
  word: IWord;
  showTable = false;


  @Input() wordArea: string;
  @Input() idArea: number;

  addWordMessage: string;


  categoryItems: string[] = ['Category...', 'awl','stem', 'hi', 'med', 'low'];
  category: string = this.categoryItems[0];

  sessionHistory: string[] = [];
  index = 1;

  constructor(private _admin: AdminService, public router: Router) { }

Here's the iterative function that I'll be utilizing:

 addWord(wordArea:string, category:string): void {
    this.processing = true;
    this.error = false;
    this.errorAdd = false;
    this._admin.postWord(wordArea, category)
      .subscribe
      (res => {
        this.processing = false;
        this.sessionHistory[this.index] = wordArea + ' is added to ' + category + ' category.'
        this.index++;
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('Client-side Error occured');
        } else {
          this.errorAdd = true;
          this.processing = false;
          console.log('Server-side Error occured');
        }
      }
      );
  }

Here are the functions I've developed up to now:

 fileUploadListener($event:any):void{

    this.csvadd($event.target, this.addWord);
    console.log('out of it');

   }

  csvadd(csv: any, callback): void { console.log('here')
    var file:File = csv.files[0];
    var self = this;
    var reader:FileReader = new FileReader();
    var wordArea:string;
    var category:string;
    var array;
    var fields;
    this.processing = true;
    this.error = false;
    this.errorAdd = false;

    console.log('getting ready to read CSV file')

    reader.readAsText(file);

    reader.onloadend = function (e) {
             var csvData = reader.result;
             console.log(csvData);
             fields = csvData.split('\n');


             for (let i in fields) {
              console.log('in loop'); 
              var array = fields[i].split(',');
              console.log(array);
              wordArea=array[0];
              console.log(wordArea);
              category=array[1];
              console.log(category);
              callback(wordArea, category);
              console.log('finished adding word')}

         };

         reader.onerror = function () {
             console.log('Unable to read ' + file);
         };



  }

Based on my understanding of TypeScript and JavaScript, using a callback function is necessary in this scenario to capture data from the file reader. However, despite implementing this approach, the functionality did not work as expected.

Do you think I'm approaching this task correctly? Should I consider an alternative method, or is there a crucial element that I may have overlooked?

Thank you!

Answer №1

When sending your callback function, it's important to use bind or arrow functions to ensure that this references the desired class and not just the function itself.

this.csvadd($event.target, this.addWord.bind(this));

Alternatively, you can also use:

this.csvadd($event.target, (wordArea, category) => this.addWord(wordArea,category));

Don't forget to update

 reader.onloadend = function(e){}

to

 reader.onloadend =(e)=>{}

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

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

How to access data within nested objects using ngFor in Ionic 4

How can I access the data I need from an API when it is nested within multiple objects? I am attempting to retrieve the full_url from the data object, which is nested inside the avatar object. I have already attempted the following: <ion-list> ...

What causes the menu icon to shift to the left upon clicking it?

I'm currently working on a website project that involves implementing a fixed navbar with jQuery sliding animation for the menu. However, I've encountered an issue where the "menu_icon" is getting pushed to the left every time the menu slides dow ...

Exploring Angular 4: Leveraging mockRespond in Conjunction with RxJS Observables

I recently completed the development of an application that is functioning smoothly. Now, I am in the process of creating a test for it. The core functionality involves fetching items from an API backend: export class CatfactService { constructor(p ...

Tips for creating a JSON cross-domain call in PHP

Hello, I'm just starting to dive into JSON cross domain. I've encountered an issue that I need help with. I am trying to make a cross-domain call to PHP using JSON, but I keep encountering errors. Here is a snippet of the code that I'm worki ...

The missing binding.node file is causing an issue with Node-sass

Previously, my angular project 7.1 was running smoothly until I upgraded to ubuntu 19.10 and encountered an error upon running npm install: > [email protected] install /home/gabb/dev/homepage/node_modules/node-sass > node scripts/install.js Do ...

Is the user currently accessing the website in multiple tabs?

I am currently working on detecting the online status of users and need to update it when the tab is closed. The challenge I am facing is determining if the user has multiple tabs open so that the status remains the same, only updating when there are no ...

What is the best way to detect and handle the destroy event in Kendo UI grids when a click event

How can I trigger a function when the delete button in a grid is clicked using JavaScript? ...

Utilize jQuery function within an HTML form

I am trying to integrate my jQuery function with an HTML tag for my login form that connects to an Azure database. I want a modal pop-up to appear when the client presses the Login button, displaying a specific message based on whether the user is in the d ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

What is the method for utilizing a class variable without assigning a value to it initially

class testClass { student: { name: string, age: number } constructor(options?: any) { this.student = { name: '', age: 0 }; } setStudent(name:string, age:number) { this.student.name ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

Incorporate a distinct, unique value from a JSON dataset into each iteration of the .each statement

My code includes an each statement that looks like this: $.each(data, function(i, value) { sublayers.push({ sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "=&ap ...

Deactivate the button for each package based on a specific PHP value

Are you looking to purchase a package or multiple packages? The available packages are displayed in the table below. I would like to implement a feature where once a user buys a package, the corresponding button for that package is disabled. Here is my cu ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

What could be causing the tooltip to not function properly with data-html="true"?

I am having trouble with customizing a tooltip. The data-html="true" attribute is not working as expected, and I can't seem to figure out what the issue is. .tooltip-custom { display: inline; position: relative; } ...

The routing system in Angular 4 seems to have trouble functioning properly when accessed from within the Laravel public folder

Currently, I am facing a challenge with deploying my Laravel JSON API which is being used by an Angular 4 application. During deployment, I utilize Forge and place the contents of the "dist" folder within Laravel's public directory. However, I am enco ...