Skip to main content

Chat

createPeopleCache

A cache of people's names, photos or profiles for an app's avatars and message names, read from your service in batches. A person asked for again while their read is queued or under way joins that read. A person the service has nothing for is kept as missing until missingFor runs out, so they are not asked about on every load. When the service fails, every read pauses, and the people in that read are asked again after it; the pause starts at pauseFor and doubles with each round that fails, up to longestPause, however many reads fail in a round. A service's Retry-After is honoured as given when it is longer. A person refused alone is missing and makes no one wait. With storage, what was read survives a reload; an entry whose time has run out is read again when next asked for, or at once while it is watched.

import { createPeopleCache } from "@/lib/ouro/people-cache";

Example

const photos = createPeopleCache<string>({
  read: async (ids) => {
    const entries = await Promise.all(ids.map(async (id) => {
      const response = await fetch(`/api/people/${id}/photo`);
      if (!response.ok) return [id, readFailure(response.status)] as const;
      return [id, { value: URL.createObjectURL(await response.blob()) }] as const;
    }));
    return Object.fromEntries(entries);
  },
  storage: webStorage("people-photos"),
});

Usage

Use one cache per kind of thing (names, photos), made once outside your components, and read it with usePerson in React or get, load and watch elsewhere.

Parameters

options
Type: PeopleCacheOptions<T>

Returns

PeopleCache<T>