store-data-structures

lobehub/lobehub

Паттерны структуры данных в сторах Zustand LobeHub. Для проектирования состояния стора, разделения списка и деталей, нормализованных map, редьюсеров, messagesMap, topicsMap или выбора общих источников типов.

Звёзды85 733
Авторlobehub
Установок2,4K

Установка

SKILL.md

LobeHub Store Data Structures

How to structure data in Zustand stores for fast list rendering, multi-detail caching, and ergonomic optimistic updates.

Core Principles

✅ DO

  1. Separate List and Detail — different structures for list pages and detail pages
  2. Use Map for Details — cache multiple detail pages with Record<string, Detail>
  3. Use Array for Lists — simple arrays for list display
  4. Types from @lobechat/types — never use @lobechat/database types in stores
  5. Distinguish List and Detail types — List types may have computed UI fields

❌ DON'T

  1. Don't use a single detail object — can't cache multiple pages
  2. Don't mix List and Detail types — they have different purposes
  3. Don't use database types — use types from @lobechat/types
  4. Don't use Map for lists — simple arrays are sufficient

Type Definitions

Each entity gets its own file under @lobechat/types/. Each file exports two types:

  • Detail type — full entity, including heavy fields (rubrics, content, editor state, …)
  • List item type — a subset that excludes heavy fields, may add computed UI fields (counts, timestamps formatted for display)

Important: the List type is a subset, not an extends of Detail. Extending pulls the heavy fields right back in.

See references/types.md for full worked examples (Benchmark, Document) and the heavy-field exclusion checklist.


When to Use Map vs Array

Use Map + Reducer — for Detail Data

✅ Detail page data caching — multiple detail pages cached simultaneously ✅ Optimistic updates — update UI before API responds ✅ Per-item loading states — track which items are being updated ✅ Multi-page navigation — user can switch between details without refetching

benchmarkDetailMap: Record<string, AgentEvalBenchmark>;

Examples: benchmark detail pages, dataset detail pages, user profiles.

Use Simple Array — for List Data

✅ List display — lists, tables, cards ✅ Refresh as a whole — entire list refreshes together ✅ No per-item updates — no need to mutate individual rows in place ✅ Simple data flow — fewer moving parts

benchmarkList: AgentEvalBenchmarkListItem[];

Examples: benchmark list, dataset list, user list.


State Structure Pattern

// src/store/eval/slices/benchmark/initialState.ts
import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';

export interface BenchmarkSliceState {
  // List — simple array
  benchmarkList: AgentEvalBenchmarkListItem[];
  benchmarkListInit: boolean;

  // Detail — map for multi-entity caching
  benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
  loadingBenchmarkDetailIds: string[]; // per-item loading

  // Mutation states (drive form-level UI)
  isCreatingBenchmark: boolean;
  isUpdatingBenchmark: boolean;
  isDeletingBenchmark: boolean;
}

export const benchmarkInitialState: BenchmarkSliceState = {
  benchmarkList: [],
  benchmarkListInit: false,
  benchmarkDetailMap: {},
  loadingBenchmarkDetailIds: [],
  isCreatingBenchmark: false,
  isUpdatingBenchmark: false,
  isDeletingBenchmark: false,
};

Reducer Pattern (for Detail Map)

When the Detail Map needs optimistic updates (i.e. the user edits a row and the UI should reflect it before the server confirms), wire a typed reducer instead of inlining set calls. This keeps mutations testable and the dispatch surface small.

See references/reducer.md for the full discriminated-union action types, the produce-based reducer, and the internal_dispatch* slice methods that connect them to Zustand.


Data Structure Comparison

❌ WRONG — Single Detail Object

interface BenchmarkSliceState {
  benchmarkDetail: AgentEvalBenchmark | null;
  isLoadingBenchmarkDetail: boolean;
}

Problems:

  • Can only cache one detail page at a time
  • Switching between details forces refetch
  • No optimistic updates
  • No per-item loading states

✅ CORRECT — Separate List and Detail

interface BenchmarkSliceState {
  benchmarkList: AgentEvalBenchmarkListItem[];
  benchmarkListInit: boolean;

  benchmarkDetailMap: Record<string, AgentEvalBenchmark>;
  loadingBenchmarkDetailIds: string[];

  isCreatingBenchmark: boolean;
  isUpdatingBenchmark: boolean;
  isDeletingBenchmark: boolean;
}

Benefits:

  • Cache multiple detail pages
  • Fast navigation between cached details
  • Optimistic updates via reducer
  • Per-item loading states
  • Clear separation of concerns

Component Usage

Accessing List Data

const BenchmarkList = () => {
  const benchmarks = useEvalStore((s) => s.benchmarkList);
  const isInit = useEvalStore((s) => s.benchmarkListInit);

  if (!isInit) return <Loading />;
  return (
    <div>
      {benchmarks.map((b) => (
        <BenchmarkCard key={b.id} name={b.name} testCaseCount={b.testCaseCount} />
      ))}
    </div>
  );
};

Accessing Detail Data

const BenchmarkDetail = () => {
  const { benchmarkId } = useParams<{ benchmarkId: string }>();

  const benchmark = useEvalStore((s) =>
    benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,
  );
  const isLoading = useEvalStore((s) =>
    benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,
  );

  if (!benchmark) return <Loading />;
  return (
    <div>
      <h1>{benchmark.name}</h1>
      {isLoading && <Spinner />}
    </div>
  );
};

Using Selectors (Recommended)

// src/store/eval/slices/benchmark/selectors.ts
export const benchmarkSelectors = {
  getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],
  isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>
    s.loadingBenchmarkDetailIds.includes(id),
};

// In component
const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));
const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(benchmarkId!));

Decision Tree

Need to store data?
│
├─ Is it a LIST for display?
│  └─ ✅ Use simple array: `xxxList: XxxListItem[]`
│     - May include computed fields
│     - Refreshed as a whole
│     - No optimistic updates needed
│
└─ Is it DETAIL page data?
   └─ ✅ Use Map: `xxxDetailMap: Record<string, Xxx>`
      - Cache multiple details
      - Support optimistic updates
      - Per-item loading states
      - Requires reducer for mutations

Checklist

When designing store state structure:

  • Organize types by entity in separate files (e.g. benchmark.ts, agentEvalDataset.ts)
  • <!-- -->Create Detail type (full entity with all fields including heavy ones)
  • <!-- -->Create ListItem type:<!-- -->
    • <!-- -->Subset of Detail (exclude heavy fields)
    • <!-- -->May include computed statistics for UI
    • NOT extends Detail
  • <!-- -->Use array for list data: xxxList: XxxListItem[]
  • <!-- -->Use Map for detail data: xxxDetailMap: Record<string, Xxx>
  • <!-- -->Per-item loading: loadingXxxDetailIds: string[]
  • Reducer for detail map if optimistic updates needed (see references/reducer.md)
  • Internal dispatch and loading methods
  • Selectors for clean access (optional but recommended)
  • <!-- -->Document in comments which fields are excluded from List and why

Best Practices

  1. File organization — one entity per file, not mixed
  2. List is a subset — ListItem excludes heavy fields, does not extends Detail
  3. Clear naming — xxxList for arrays, xxxDetailMap for maps
  4. Consistent patterns — all detail maps follow the same shape
  5. Type safety — never use any, always use proper types
  6. Document exclusions — comment which fields are excluded and why
  7. Selectors — encapsulate access patterns
  8. Loading states — per-item for details, global for mutations
  9. Immutability — use Immer in reducers

Common Mistakes to Avoid

❌ DON'T extend Detail in List:

// Wrong — pulls heavy fields back in
export interface BenchmarkListItem extends Benchmark {
  testCaseCount?: number;
}

✅ DO create separate subset:

export interface BenchmarkListItem {
  id: string;
  name: string;
  // ... only necessary fields
  testCaseCount?: number; // Computed
}

❌ DON'T mix entities in one file:

// Wrong — all entities in agentEvalEntities.ts

✅ DO separate by entity:

// Correct — separate files
// benchmark.ts
// agentEvalDataset.ts
// agentEvalRun.ts

Related Skills

  • data-fetching-architecture — how to fetch and update this data
  • zustand — general Zustand patterns

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: store-data-structures](https://darkplay.ru/ai/skills/lobehub-lobehub-store-data-structures)

Описание

Паттерны формы данных в сторах Zustand в LobeHub. Используй при проектировании состояния стора, разделении списков и деталей, нормализованных мапах, редьюсерах, messagesMap, topicsMap или выборе источников общих типов.

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Database Migrationaffaan-m · Каркас команды workflow для database-migration в everything-claude-code.
225 587 ★
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Evolveaffaan-m · Анализирует инстинкты и предлагает или генерирует эволюционировавшие структуры.
225 587 ★
Healthcare Revieweraffaan-m · Проверяет медицинский код: клиническая безопасность, CDSS, PHI и целостность данных.
225 587 ★
Mle Revieweraffaan-m · Ревьюер ML-инженерии: данные, признаки, обучение, оценка, сервинг и мониторинг.
225 587 ★
Pytorch Build Resolveraffaan-m · Специалист по ошибкам PyTorch: формы тензоров, CUDA, градиенты и DataLoader.
225 587 ★
Security Revieweraffaan-m · Ищет и устраняет уязвимости: секреты, SSRF, инъекции, крипто и OWASP Top 10.
225 587 ★
Seo Specialistaffaan-m · SEO-специалист: технический аудит, оптимизация страниц, структурированные данные, Core…
225 587 ★
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8