Skip to content

useFormulaConfiguration

Paulo Gomes da Cruz Junior edited this page Sep 11, 2026 · 1 revision

useFormulaConfiguration Hooks

Type: Hook Domain: Frontend — Configuration Data Fetching File: src/hooks/useFormulaConfiguration/index.ts Last updated: 2026-09-10 Status: Current

Overview

The useFormulaConfiguration hooks provide the TanStack Query (React Query) layer for formula configuration data. They wrap the FormulaConfigurationService with query keys, caching, invalidation, and mutation logic. These hooks are the primary interface for pages to fetch and mutate formula sets.

Public Interface

Query Keys

export const formulaConfigurationKeys = {
  all: ["formulaConfiguration"] as const,
  lists: () => [...formulaConfigurationKeys.all, "list"] as const,
  list: (params: PageableRequest<FormulaSetResponse>) =>
    [...formulaConfigurationKeys.lists(), params] as const,
  effective: (params: FormulaSetEffectiveParams) =>
    [...formulaConfigurationKeys.all, "effective", params] as const,
  detail: (id: number) =>
    [...formulaConfigurationKeys.all, "detail", id] as const,
};
Key Factory Returns Use Case
formulaConfigurationKeys.all ['formulaConfiguration'] Base key for broad invalidation
formulaConfigurationKeys.lists() ['formulaConfiguration', 'list'] Invalidate all list queries
formulaConfigurationKeys.list(params) ['formulaConfiguration', 'list', params] Specific paginated list
formulaConfigurationKeys.effective(params) ['formulaConfiguration', 'effective', params] Date-effective lookup
formulaConfigurationKeys.detail(id) ['formulaConfiguration', 'detail', id] Single set detail (not currently used)

Queries

useFormulaSetList(params)

Fetches a paginated list of formula sets.

export function useFormulaSetList(params: PageableRequest<FormulaSetResponse>);
Parameter Type Description
params PageableRequest<FormulaSetResponse> { page: number, size: number, sort?: string[] }

Returns: UseQueryResult<FormulaSetListResponse, Error>

Query Config:

  • queryKey: formulaConfigurationKeys.list(params)
  • queryFn: () => formulaConfiguration.getFormulaSets(params)
  • placeholderData: keepPreviousData (smooth pagination transitions)

Usage:

const { data, isLoading, isError, error, refetch } = useFormulaSetList({
  page: 0,
  size: 20,
  sort: ["startDate,DESC"],
});
const formulaSets = data?.content ?? [];
const totalPages = data?.page.totalPages ?? 0;

useEffectiveFormulaSet(params, enabled)

Fetches the formula set effective for a given date and area.

export function useEffectiveFormulaSet(
  params: FormulaSetEffectiveParams,
  enabled = true,
);
Parameter Type Description
params FormulaSetEffectiveParams { date: 'YYYY-MM-DD', area: 'INTERIOR' | 'COASTAL' }
enabled boolean Default true — set false to disable

Returns: UseQueryResult<FormulaSetResponse, Error>

Query Config:

  • queryKey: formulaConfigurationKeys.effective(params)
  • queryFn: () => formulaConfiguration.getEffectiveFormulaSet(params)
  • enabled: enabled && !!params.date && !!params.area

Usage:

const { data: effectiveSet } = useEffectiveFormulaSet(
  { date: "2026-09-10", area: "INTERIOR" },
  !!selectedDate && !!selectedArea,
);

Mutations

useCreateFormulaSet()

Creates a new formula set. Invalidates list queries on success.

export function useCreateFormulaSet();

Returns: UseMutationResult<FormulaSetResponse, Error, FormulaSetRequest, unknown>

Mutation Config:

  • mutationFn: (dto) => formulaConfiguration.createFormulaSet(dto)
  • onSuccess: Invalidates formulaConfigurationKeys.lists()

Usage:

const createMutation = useCreateFormulaSet();
await createMutation.mutateAsync({
  area: 'INTERIOR',
  startDate: '2026-09-10',
  endDate: null,
  formulas: [...],
});

useUpdateFormulaSet()

Updates a formula set with complete replacement. Invalidates list queries and updates detail cache on success.

export function useUpdateFormulaSet();

Returns: UseMutationResult<FormulaSetResponse, Error, { id: number; dto: FormulaSetRequest }, unknown>

Mutation Config:

  • mutationFn: ({ id, dto }) => formulaConfiguration.updateFormulaSet(id, dto)
  • onSuccess:
    • Invalidates formulaConfigurationKeys.lists()
    • Sets formulaConfigurationKeys.detail(updated.id) cache

Usage:

const updateMutation = useUpdateFormulaSet();
await updateMutation.mutateAsync({
  id: 5,
  dto: { area: 'INTERIOR', startDate: '2026-09-10', endDate: '2026-12-31', formulas: [...] },
});

useDeleteFormulaSet()

Soft-deletes a future open-ended formula set. Invalidates list queries and removes detail cache on success.

export function useDeleteFormulaSet();

Returns: UseMutationResult<void, Error, number, unknown>

Mutation Config:

  • mutationFn: (id) => formulaConfiguration.deleteFormulaSet(id)
  • onSuccess:
    • Invalidates formulaConfigurationKeys.lists()
    • Removes formulaConfigurationKeys.detail(id) cache

Usage:

const deleteMutation = useDeleteFormulaSet();
await deleteMutation.mutateAsync(5);

Types

All types imported from @/services/formulaConfiguration.types:

Type Description
FormulaSetResponse Full formula set with ID, dates, formulas, timestamps
FormulaSetRequest Create/update payload (area, startDate, endDate, formulas)
FormulaSetEffectiveParams Date-effective lookup params (date, area)
FormulaItemDto Single formula (key, expression, variables, errors, sortOrder)
FormulaValidationError Backend validation error (code, message, offsets)
FormulaSetListResponse Paginated response (content + page metadata)
PageableRequest<T> Pagination params (page, size, sort)

Dependencies

Inward (Imports)

Module Purpose
@tanstack/react-query keepPreviousData, useMutation, useQuery, useQueryClient
@/services/APIs API.formulaConfiguration service instance
@/services/formulaConfiguration.types All DTO types
@/services/types PageableRequest

Outward (Consumed By)

Consumer Hooks Used
FormulaConfigurationList useFormulaSetList
FormulaConfigurationDetail useFormulaSetList, useCreateFormulaSet, useUpdateFormulaSet, useDeleteFormulaSet
Calculation pages (future) useEffectiveFormulaSet

Known Constraints

  • No detail query hook — formulaConfigurationKeys.detail(id) exists but no useFormulaSetDetail(id) hook; pages use list data or mutation cache
  • No optimistic updates — UI waits for mutation success; no rollback on error
  • List invalidation on all mutations — create, update, delete all invalidate lists(); could be granular
  • keepPreviousData only on list — effective query doesn't use placeholder data
  • Error handling delegated — mutations return raw errors; pages must handle isError/error
  • Query key includes full params object — sorting/page changes create new cache entries (correct)

Usage Example

// In a page component
import {
  useFormulaSetList,
  useEffectiveFormulaSet,
  useCreateFormulaSet,
  useUpdateFormulaSet,
  useDeleteFormulaSet,
} from "@/hooks/useFormulaConfiguration";

// List with pagination
const { data, isLoading, refetch } = useFormulaSetList({
  page: currentPage,
  size: 20,
  sort: ["startDate,DESC"],
});

// Date-effective lookup (for calculation engine integration)
const { data: effectiveSet } = useEffectiveFormulaSet(
  { date: calculationDate, area: selectedArea },
  !!calculationDate && !!selectedArea,
);

// Mutations
const createMutation = useCreateFormulaSet();
const updateMutation = useUpdateFormulaSet();
const deleteMutation = useDeleteFormulaSet();

// In event handlers
await createMutation.mutateAsync(newSetDto);
await updateMutation.mutateAsync({ id: setId, dto: updatedDto });
await deleteMutation.mutateAsync(setId);

Testing

Unit tests in src/hooks/useFormulaConfiguration/index.unit.test.ts:

  • 2416 tests passing (combined with service tests)
  • Covers query key factories, query configs, mutation configs
  • Mocks FormulaConfigurationService methods
  • Verifies invalidation logic

Related Pages

Waste Plus Wiki

Home

Architecture

Codes

Decisions

Knowledge Base

Development

Changes

Clone this wiki locally