# Endpoint Expiry Policy

By default, Reactive Data Client uses [stale-while-revalidate](https://web.dev/stale-while-revalidate/). When data is
available, components render it immediately. If the data is old enough, Data Client refetches it in the background.

## Expiry status

### Fresh

The data is new enough. Data Client does not fetch it.

### Stale

Components can show the data. Data Client fetches it again when a component needs it.

### Invalid

Components cannot show the data. A component that needs it fetches it and suspends. If no component needs the
data, nothing happens.

[useSuspense()](https://dataclient.io/docs/api/useSuspense.md) checks the data on mount and when its parameters change. It fetches if the
data is stale.

> **Info: React Native**
>
> When using React Navigation, [focus events](https://reactnavigation.org/docs/use-focus-effect/) also trigger fetches for stale data.

## Expiry Time

### Endpoint.dataExpiryLength

[Endpoint.dataExpiryLength](https://dataclient.io/rest/api/Endpoint.md#dataexpirylength) sets how many milliseconds data stays
'[fresh](#fresh)' before it becomes '[stale](#stale)'. Set it to a low number like `50` to make data
[stale](#stale) almost immediately, or to a large number to keep it fresh for a long time.

Toggling between 'first' and 'second' changes the parameters. While the data is fresh,
the old time stays without a refetch.

Files with a `route` are pages mounted at that path, with its params as props; `Link` and `useNavigate()` stand for your router (with react-router, read params with `useParams()`).

```ts title="api/lastUpdated"
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});
```

```ts title="getUpdated"
import { lastUpdated } from './api/lastUpdated';

export const getUpdated = lastUpdated.extend({ dataExpiryLength: 10000 });
```

```tsx title="TimePage" route="/time/:id" start="/time/1"
import { useSuspense } from '@data-client/react';
import { getUpdated } from './getUpdated';

export default function TimePage({ id }: { id: string }) {
  const { updatedAt } = useSuspense(getUpdated, { id });
  return (
    <>
      <h2>
        <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'medium' })}</time>
      </h2>
      <span className="meta">Fetched for page {id}</span>
    </>
  );
}
```

```tsx title="Navigator" layout
export default function Navigator({ children }) {
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Server time</h1>
        <CurrentTime />
      </header>
      <nav>
        <Link to="/time/1">First</Link>
        <Link to="/time/2">Second</Link>
      </nav>
      {children}
    </>
  );
}
```

<details>

<summary>@data-client/rest</summary>

Long cache lifetime

```typescript title="LongLivingResource.ts"
import {
  RestEndpoint,
  RestGenerics,
  resource,
} from '@data-client/rest';

// We can now use LongLivingEndpoint to create endpoints that will be cached for one hour
class LongLivingEndpoint<
  O extends RestGenerics,
> extends RestEndpoint<O> {
  dataExpiryLength = 60 * 60 * 1000; // one hour
}

const LongLivingResource = resource({
  path: '/:id',
  Endpoint: LongLivingEndpoint,
});
```

Never retry on error

```typescript title="NoRetryResource.ts"
import {
  RestEndpoint,
  RestGenerics,
  resource,
} from '@data-client/rest';

// We can now use NoRetryEndpoint to create endpoints that will be cached for one hour
class NoRetryEndpoint<
  O extends RestGenerics,
> extends RestEndpoint<O> {
  errorExpiryLength = Infinity;
}

const NoRetryResource = resource({
  path: '/:id',
  Endpoint: NoRetryEndpoint,
});
```

</details>

### Endpoint.invalidIfStale

[Endpoint.invalidIfStale](https://dataclient.io/rest/api/Endpoint.md#invalidifstale) eliminates the '[stale](#stale)' status, making data
that expires immediately be considered '[invalid](#invalid)'.

This is demonstrated by the page suspending once its data goes stale (navigation waits on the progress bar).
While the data is fresh, the page shows it.

Files with a `route` are pages mounted at that path, with its params as props; `Link` and `useNavigate()` stand for your router (with react-router, read params with `useParams()`).

```ts title="api/lastUpdated"
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});
```

```ts title="getUpdated"
import { lastUpdated } from './api/lastUpdated';

export const getUpdated = lastUpdated.extend({
  invalidIfStale: true,
  dataExpiryLength: 5000,
});
```

```tsx title="TimePage" route="/time/:id" start="/time/1"
import { useSuspense } from '@data-client/react';
import { getUpdated } from './getUpdated';

export default function TimePage({ id }: { id: string }) {
  const { updatedAt } = useSuspense(getUpdated, { id });
  return (
    <>
      <h2>
        <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'medium' })}</time>
      </h2>
      <span className="meta">Fetched for page {id}</span>
    </>
  );
}
```

```tsx title="Navigator" layout
export default function Navigator({ children }) {
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Server time</h1>
        <CurrentTime />
      </header>
      <nav>
        <Link to="/time/1">First</Link>
        <Link to="/time/2">Second</Link>
      </nav>
      {children}
    </>
  );
}
```

## Force refresh

To fetch new data while you show the old data:

### A specific endpoint

[Controller.fetch](https://dataclient.io/docs/api/Controller.md#fetch) fetches while components show the previous data. It fetches even
when the data is 'fresh'.

```ts title="api/lastUpdated"
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});
```

```tsx title="ShowTime"
import { useSuspense, useController } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';

function ShowTime() {
  const { updatedAt } = useSuspense(lastUpdated, { id: '1' });
  const ctrl = useController();
  return (
    <>
      <div className="listItem">
        <span className="meta">API time</span>
        <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'long' })}</time>
      </div>
      <button onClick={() => ctrl.fetch(lastUpdated, { id: '1' })}>
        Refresh
      </button>
    </>
  );
}
render(<ShowTime />);
```

### Refresh visible endpoints

[Controller.expireAll()](https://dataclient.io/docs/api/Controller.md#expireAll) sets all responses' [expiry status](#expiry-status) matching `testKey` to [Stale](#stale).

```ts title="api/lastUpdated"
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});
```

```tsx title="TimeList"
import { AsyncBoundary, useSuspense } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';

const ids = ['1', '2', '3'];

export default function TimeList() {
  return ids.map(id => (
    <AsyncBoundary key={id} fallback={<TimeSkeleton id={id} />}>
      <TimeRow id={id} />
    </AsyncBoundary>
  ));
}

function TimeRow({ id }: { id: string }) {
  const { updatedAt } = useSuspense(lastUpdated, { id });
  return (
    <div className="listItem">
      <b>{id}</b>
      <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'long' })}</time>
    </div>
  );
}

function TimeSkeleton({ id }: { id: string }) {
  return (
    <div className="listItem">
      <b>{id}</b>
      <span className="skeleton" />
    </div>
  );
}
```

```tsx title="Demo"
import { useController } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';
import TimeList from './TimeList';

function Demo() {
  const ctrl = useController();
  return (
    <div>
      <TimeList />
      <div className="buttonGroup">
        <button onClick={() => ctrl.expireAll(lastUpdated)}>
          Expire All
        </button>
        <button onClick={() => ctrl.fetch(lastUpdated, { id: '1' })}>
          Force Refresh First
        </button>
      </div>
    </div>
  );
}
render(<Demo />);
```

## Invalidate (re-suspend) {#invalidate}

Both [endpoints](https://dataclient.io/rest/api/Endpoint.md) and [entities](https://dataclient.io/rest/api/Entity.md) can be invalidated.

### A specific endpoint {#invalidate-endpoint}

In this example [invalidating the endpoint](https://dataclient.io/docs/api/Controller.md#invalidate) shows the loading fallback since the data is not allowed to be displayed.

```ts title="api/lastUpdated"
import { Entity, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});
```

```tsx title="TimeList"
import { AsyncBoundary, useSuspense } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';

const ids = ['1', '2', '3'];

export default function TimeList() {
  return ids.map(id => (
    <AsyncBoundary key={id} fallback={<TimeSkeleton id={id} />}>
      <TimeRow id={id} />
    </AsyncBoundary>
  ));
}

function TimeRow({ id }: { id: string }) {
  const { updatedAt } = useSuspense(lastUpdated, { id });
  return (
    <div className="listItem">
      <b>{id}</b>
      <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'long' })}</time>
    </div>
  );
}

function TimeSkeleton({ id }: { id: string }) {
  return (
    <div className="listItem">
      <b>{id}</b>
      <span className="skeleton" />
    </div>
  );
}
```

```tsx title="Demo"
import { useController } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';
import TimeList from './TimeList';

function Demo() {
  const ctrl = useController();
  return (
    <div>
      <TimeList />
      <div className="buttonGroup">
        <button onClick={() => ctrl.invalidateAll(lastUpdated)}>
          Invalidate All
        </button>
        <button onClick={() => ctrl.invalidate(lastUpdated, { id: '1' })}>
          Invalidate First
        </button>
      </div>
    </div>
  );
}
render(<Demo />);
```

### Any endpoint with an entity {#invalidate-entity}

The [Invalidate schema](https://dataclient.io/rest/api/Invalidate.md) invalidates _every_ endpoint whose response includes that
[entity](https://dataclient.io/rest/api/Entity.md). If the endpoint has the entity in an [Array](https://dataclient.io/rest/api/Array.md), Data Client removes it from
that [Array](https://dataclient.io/rest/api/Array.md).

```ts title="api/lastUpdated"
import { Entity, Invalidate, RestEndpoint } from '@data-client/rest';
import { Temporal } from 'temporal-polyfill';

export class TimedEntity extends Entity {
  id = '';
  updatedAt = Temporal.Instant.fromEpochMilliseconds(0);

  static schema = {
    updatedAt: Temporal.Instant.from,
  };
}

export const lastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  schema: TimedEntity,
});

export const InvalidateTimedEntity = new Invalidate(TimedEntity);

export const deleteLastUpdated = new RestEndpoint({
  path: '/api/currentTime/:id',
  method: 'DELETE',
  schema: InvalidateTimedEntity,
});
```

```tsx title="ServerTime"
import { AsyncBoundary, useSuspense } from '@data-client/react';
import { lastUpdated } from './api/lastUpdated';

export default function ServerTime({ id }: { id: string }) {
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Server time</h1>
        <CurrentTime />
      </header>
      <section>
        <AsyncBoundary
          fallback={
            <h2>
              <span className="skeleton" />
            </h2>
          }
        >
          <TimeReadout id={id} />
        </AsyncBoundary>
      </section>
    </>
  );
}

function TimeReadout({ id }: { id: string }) {
  const { updatedAt } = useSuspense(lastUpdated, { id });
  return (
    <h2>
      <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'medium' })}</time>
    </h2>
  );
}
```

```tsx title="ShowTime"
import { useController, useLoading } from '@data-client/react';
import {
  InvalidateTimedEntity,
  deleteLastUpdated,
} from './api/lastUpdated';
import ServerTime from './ServerTime';

function ShowTime() {
  const ctrl = useController();
  const [handleDelete, loadingDelete] = useLoading(
    () => ctrl.fetch(deleteLastUpdated, { id: '1' }),
    [],
  );
  return (
    <div>
      <ServerTime id="1" />
      <div className="buttonGroup">
        <button onClick={handleDelete} aria-busy={loadingDelete}>
          Invalidate
        </button>
        <button
          onClick={() =>
            ctrl.setResponse(deleteLastUpdated, { id: '1' }, { id: '1' })
          }
        >
          Invalidate (without fetching DELETE)
        </button>
        <button
          onClick={() => ctrl.set([InvalidateTimedEntity], [{ id: '1' }])}
        >
          Invalidate Entity with ctrl.set
        </button>
      </div>
    </div>
  );
}
render(<ShowTime />);
```

[Controller.fetch()](https://dataclient.io/docs/api/Controller.md#fetch) updates the server and the store. To change only the store, use
[Controller.setResponse()](https://dataclient.io/docs/api/Controller.md#setResponse) or [Controller.set()](https://dataclient.io/docs/api/Controller.md#set).

#### Conditional Invalidation based on data

To invalidate only for some responses, return `undefined` from [Entity.process](https://dataclient.io/rest/api/Entity.md#process).

```ts
class PriceLevel extends Entity {
  price = 0;
  amount = 0;

  pk() {
    return this.price;
  }

  static process(
    input: [number, number],
    parent: any,
    key: string | undefined,
  ): any {
    const [price, amount] = input;
    if (amount === 0) return undefined;
    return { price, amount };
  }
}
```
