# Working with Data

> Learn how to visualise and manage your data in new ways with Infinite Table

Canonical page: https://infinite-table.com/angular/docs/learn/working-with-data/

When working with data, you will mostly interact with the `<DataSource />` component, which is responsible for handling and managing the data and passing it down to the `<InfiniteTable />` component, which is the rendering engine for the DataGrid.

So we provide those two components (as named exports) inside `@infinite-table/infinite-angular` package:

- `<DataSource />` - our data-handling component
- `<InfiniteTable />` - our virtualized component

The `<DataSource/>` component is responsible for the data the management layer.

Probably the most important prop for the `<DataSource />` component is the [`primaryKey`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#primaryKey) prop. It specifies the property of the data object that is used as a unique identifier for data rows/items.

```ts
<!-- data can also be a Promise or a function returning a Promise -->
<infinite-data-source primaryKey="id" [data]="data" />
```

The `DataSource` component (`<infinite-data-source>`) is a generic class, bound to an array of items of the generic type. In a template you don't pass the type: with `strictTemplates`, Angular infers it from the inputs you bind, so type the values you bind with it: `DataSourceData<DATA_TYPE>` for the `data` input, `InfiniteTablePropColumns<DATA_TYPE>` for the columns.

In this documentation, we'll use `DATA_TYPE` when referring to the generic type. Rarely, we'll use `T`.

```ts
import type {
  DataSourceData,
  InfiniteTablePropColumns,
} from '@infinite-table/infinite-angular';

@Component({
  selector: 'data-grid',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source primaryKey="id" [data]="data">
      <infinite-table [columns]="columns" />
    </infinite-data-source>
  `,
})
export class DataGrid {
  protected readonly data: DataSourceData<DATA_TYPE> = [
    /* ... */
  ];
  protected readonly columns: InfiniteTablePropColumns<DATA_TYPE> = {
    /* ... */
  };
}
```

Most of our examples in these docs have a `Developer` or `Employee` TypeScript data type used as the generic type.

```ts
import { DataSource } from '@infinite-table/infinite-angular';

type Employee = {
  id: string | number;
  name: string;
  salary: number;
  department: string;
  company: string;
};

const employees: Employee[] = [
  { id: 1, name: 'Bob', salary: 10_000, department: 'IT', company: 'Bobsons' },
  {
    id: 2,
    name: 'Alice',
    salary: 20_000,
    department: 'IT',
    company: 'Bobsons',
  },
  { id: 3, name: 'John', salary: 30_000, department: 'IT', company: 'Bobsons' },
];

@Component({
  selector: 'employees',
  imports: [DataSource],
  template: `<infinite-data-source primaryKey="id" [data]="employees" />`,
})
export class Employees {
  protected readonly employees = employees;
}
```

In the snippet above, we see 3 important details:

1. the `employees` array is typed as `Employee[]`, and the type of the `DataSource` is inferred from it
2. we use a `primaryKey` input - here it is `id`, which is a property of the `Employee` type
3. we pass the `employees` array as the `data` input, bound with `[data]`.

The [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) prop can be either:

- an array of the bound generic type - here `Employee[]`
- a Promise tha resolves to an array like the above
- a function that returns any of the above

**Example: Data loading example with promise**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';
import type { InfiniteTableColumn } from '@infinite-table/infinite-angular';

type Employee = {
  id: string | number;
  name: string;
  salary: number;
  department: string;
  company: string;
};

const employees: Employee[] = [
  {
    id: 1,
    name: 'Bob',
    salary: 10_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 2,
    name: 'Alice',
    salary: 20_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 3,
    name: 'John',
    salary: 30_000,
    department: 'IT',
    company: 'Bobsons',
  },
  {
    id: 4,
    name: 'Jane',
    salary: 35_000,
    department: 'Marketing',
    company: 'Janies',
  },
  {
    id: 5,
    name: 'Mary',
    salary: 40_000,
    department: 'Marketing',
    company: 'Janies',
  },
];

// simulate data-loading with a 1500ms delay
const data = new Promise<Employee[]>((resolve) => {
  setTimeout(() => {
    resolve(employees);
  }, 1500);
});

const columns: Record<string, InfiniteTableColumn<Employee>> = {
  id: {
    field: 'id',
    type: 'number',
    defaultWidth: 80,
  },
  name: {
    field: 'name',
  },
  salary: { field: 'salary', type: 'number' },
  department: { field: 'department', header: 'Dep.' },
  company: { field: 'company' },
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source [data]="data" primaryKey="id">
      <infinite-table
        debugId="basic-example"
        [columnDefaultWidth]="130"
        [columns]="columns"
      />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly data = data;
  protected readonly columns = columns;
}
```

## Data Loading Strategies

We're aware there are countless strategies for loading data - each with its own strengths. We decided we should focus on building what we do best, namely building virtualized components, so we encourage you to use your preferred data-fetching library/solution. This being said, we still provide you with the flexibility you need when using the `<DataSource/>`, so here's what you can use for the [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) prop of the component:

- an array of the bound type
- a Promise that resolves to an array of the bound type
- a function that returns any of the above

While you're loading the data, you can always render a loading indicator - pass the [`[(loading)]`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#loading) prop into the component (along with [`loadingText`](https://infinite-table.com/angular/docs/reference/infinite-table-props.md#loadingText) prop in the `<InfiniteTable />` component if you want to customize the message).

### Using fetch

For basic datasets, which have simple data requirements, using `fetch` is probably sufficient, so here is an example:

**Example: Using fetch for remote data**

```ts
import { Component } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const dataSource = () => {
  return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees10k')
    .then((r) => r.json())
    .then((data: Employee[]) => {
      return data;
    });
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <infinite-data-source [data]="dataSource" primaryKey="id">
      <infinite-table debugId="using-fetch-example" [columns]="columns" />
    </infinite-data-source>
  `,
})
export default class App {
  protected readonly dataSource = dataSource;
  protected readonly columns = columns;
}
```

#### Re-fetching on change

It's important to note you can re-fetch data by changing the reference you pass as the `data` prop to the `<DataSource/>` component.

Passing another [`data`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#data) function, will cause the component to re-execute the function and thus load new data.

Alternatively, you can use the [`refetchKey`](https://infinite-table.com/angular/docs/reference/datasource-props/index.md#refetchKey) prop to trigger a re-fetch - give it a new value (eg: use it as a counter, and increment it) and the component will re-fetch the data.

**Example: Re-fetching data**

```ts
import { Component, computed, signal } from '@angular/core';

import { DataSource, InfiniteTable } from '@infinite-table/infinite-angular';

import { columns } from './columns.angular';
import type { Employee } from './columns.angular';

const getDataSourceFor = (size: string) => {
  if (size === '0') {
    return () => Promise.resolve([]);
  }
  return () => {
    return fetch(process.env.NEXT_PUBLIC_BASE_URL + '/employees' + size)
      .then((r) => r.json())
      .then((data: Employee[]) => data);
  };
};

@Component({
  selector: 'demo-root',
  imports: [DataSource, InfiniteTable],
  template: `
    <div
      style="display: flex; flex: 1; flex-flow: column; color: var(--infinite-cell-color); background: var(--infinite-background)"
    >
      <p style="padding: 10px">Please select the size of the datasource:</p>
      <div style="padding: 10px">
        <select
          style="margin: 10px 0; display: inline-block; background: var(--infinite-background); color: currentColor; padding: var(--infinite-space-3)"
          [value]="dataSourceSize()"
          (change)="onSizeChange($event)"
        >
          <option value="0">no items</option>
          <option value="10">10 items</option>
          <option value="100">100 items</option>
          <option value="1k">1k items</option>
          <option value="10k">10k items</option>
        </select>
      </div>
      <infinite-data-source [data]="dataSource()" primaryKey="id">
        <infinite-table
          debugId="refetch-example"
          [columns]="columns"
          [columnDefaultWidth]="150"
        />
      </infinite-data-source>
    </div>
  `,
})
export default class App {
  protected readonly columns = columns;

  protected readonly dataSourceSize = signal('10');

  protected readonly dataSource = computed(() =>
    getDataSourceFor(this.dataSourceSize()),
  );

  protected onSizeChange(event: Event) {
    this.dataSourceSize.set((event.target as HTMLSelectElement).value);
  }
}
```

## Live Updates

You can update your data in real-time by using our [DataSource API](https://infinite-table.com/angular/docs/reference/datasource-api/index.md).

Read more about how to use our API to update your data in real-time
