Skip to content

DistrictListing

Paulo Gomes da Cruz Junior edited this page Apr 13, 2026 · 1 revision

DistrictListing

The DistrictListing component provides a specialized implementation of DistrictSelection for displaying and selecting forest districts. It fetches district codes from the application's code service and presents them in a searchable, selectable list.

Props

This component does not accept any props. It is a self-contained implementation that manages its own data fetching and state.

Usage

import DistrictListing from '@/components/core/DistrictSelection/DistrictListing';

// Simple usage - no props needed
<DistrictListing />

Features

Data Fetching

Uses React Query to fetch district codes from the codes API:

const { data, isLoading } = useQuery({
  queryKey: ['districtOptions'],
  queryFn: async () => await APIs.codes.getDistricts(),
  staleTime: Infinity,
  enabled: true,
  select: (data) =>
    data.map((district) => ({
      id: district.code,
      name: district.description,
      kind: 'D',
    })),
});

Data Transformation

Raw district code data is transformed to match the DistrictType interface:

  • id: Maps to district.code
  • name: Maps to district.description
  • kind: Always set to 'D' (District type, maps to Location icon)

Search Functionality

Implements a simple filter function that searches across:

  • District name/description (case-insensitive, partial match)
  • District code (case-insensitive, exact match)
const filter = (client: DistrictType, keyword: string): boolean => {
  return (
    client.name.trim().toLowerCase().includes(keyword.toLowerCase()) ||
    client.id.trim().toLowerCase() === keyword.toLowerCase()
  );
};

Preference Persistence

Selected districts are stored in user preferences under the key selectedDistrict, allowing the selection to persist across sessions.

Infinite Cache Time

The query uses staleTime: Infinity, meaning district data is cached indefinitely since district codes rarely change. This improves performance by preventing unnecessary refetches.

Configuration

The component configures DistrictSelection with:

Configuration Value Purpose
preferenceKey "selectedDistrict" Key for storing selected district in preferences
deselectLabel "Select no district" Label for the deselect option
searchLabel "Search by district name or code" Placeholder text for the search input

District Icon

All districts use the 'D' kind code, which maps to the Location icon from Carbon Design System via the ClientTypeIconMap.

Dependencies

Required Context Providers

  • PreferenceProvider: Manages storage and retrieval of selected district
  • QueryClientProvider: Required for React Query functionality

API Services

  • APIs.codes.getDistricts: Fetches the list of available district codes

Example Integration

import { PreferenceProvider } from '@/context/preference/PreferenceProvider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import DistrictListing from '@/components/core/DistrictSelection/DistrictListing';

const queryClient = new QueryClient();

function MyApp() {
  return (
    <QueryClientProvider client={queryClient}>
      <PreferenceProvider>
        <DistrictListing />
      </PreferenceProvider>
    </QueryClientProvider>
  );
}

Query Behavior

Enabled Condition

The query is always enabled (enabled: true) since district data is publicly available and doesn't depend on user permissions.

Cache Key

Uses a simple query key: ['districtOptions']

Stale Time

Set to Infinity, meaning the data never becomes stale and won't refetch unless manually invalidated or the page is refreshed.

This is appropriate for district codes since they are relatively static reference data.

Accessing Selected District

To retrieve the currently selected district in other components:

import { usePreference } from '@/context/preference/usePreference';

function MyComponent() {
  const { userPreference } = usePreference();
  const selectedDistrictCode = userPreference.selectedDistrict;

  // Use selectedDistrictCode to filter data, make requests, etc.
}

Use Cases

  • Filtering waste data by geographic district
  • Restricting search results to a specific district
  • Displaying district-specific reports or dashboards
  • Setting default district preferences for users

Best Practices

  1. Wrap in PreferenceProvider: The component requires PreferenceProvider to function

  2. Consider initial load: Since districts load on mount, ensure parent components handle loading states appropriately

  3. Cache invalidation: If district codes are updated in the system, manually invalidate the query cache:

    queryClient.invalidateQueries({ queryKey: ['districtOptions'] });
  4. Error handling: Wrap usage in an ErrorBoundary to handle API failures gracefully

Performance Considerations

  • Infinite stale time: District data is cached indefinitely, reducing API calls
  • Single API call: All districts are fetched once and reused throughout the session
  • Client-side filtering: Search filtering happens in-browser, providing instant results

Related Components

  • DistrictSelection: The base component that DistrictListing extends
  • DistrictItem: Renders individual district items in the list
  • ClientListing: Similar component for client selection

Notes

  • All districts display the same icon (Location) since they share the same kind value
  • The deselect option allows users to clear district filtering
  • Search is case-insensitive and supports both code and description matching
  • The component automatically hides the search bar if fewer than 5 districts are available

Waste Plus Wiki

Home

Architecture

Codes

Decisions

Knowledge Base

Development

Changes

Clone this wiki locally