1

I used a material table as a reusable component. I call it in other component as followed.

class UserTable {
  name: string;
  vehicleId: number;
  garageId: number;
}

tableColumns: Array<Column> = [
    {
      columnDef: 'name',
      header: 'Name',
      cell: (element: Record<string, unknown>) => `${element['name']}`
    },
    {
      columnDef: 'vehicleId',
      header: 'Vehicle',
      cell: (element: Record<string, unknown>) => {
        const vehicle = this.vehicleList.find(vehicles => vehicles.id === element['vehicleId']);
        return vehicle?.name;
      }
    },
    {
      columnDef: 'garageId',
      header: 'Garage',
      cell: (element: Record<string, unknown>) => {
        const garage = this.garageList.find(garages => garages.id === element['garageId']);
        return garage?.name;
      }
    }
  ];

the User class

class User implements IUser {
  id: number;
  name: string;
  description: string;
  vehicleId: number;
  garageId: number;
}

I need to display name, vehicle Name, garage in the table. to display vehicle name, i used above code. It works, but give console error 'Cannot read properties of undefined (reading 'find')' and can't visible the garage name also.
what can i do for that?

1 Answers1

0

As per docs, arrow functions don't have binding to this and hence should not be used as methods on an object. And that's exactly what you're doing.

What this means is that this.vehicleList is probably not what you expect it to be - i.e. it reads the vehicleList property of the caller of the function, for which it's probably not defined.

Take a look at the below example for better understanding:

let def = {
  value: 'value in def',
  logValue: () => {
    // You expect this will log `value in def`, but it won't. 
    console.log(this.value)
  }
};

this.value = 'value in global scope';
console.log(def.logValue());

You should probably read more about this, arrow functions and scope to understand it better.

You might want to switch the arrow function into function expression and see if it solves your scoping issues.

TotallyNewb
  • 3,884
  • 1
  • 11
  • 16