Azure / Azure/aks-desktop

refactor: extract shared useAsync hook for loading/error/data state management

Open
#533 1 comment 0 reactions 2 assignees Claimed by @gambtho View on GitHub
bug documentation p2
Dominant language
TypeScript
Stars
102
Forks
25
Avg merge
1d 4h
Merged PRs (30d)
22

Description

## Summary

12+ hooks across the codebase independently implement the same loading/error/data `useState` pattern with manual cancellation logic. This creates ~200 lines of duplicated boilerplate and inconsistent cancellation strategies.

## Problem

The following pattern appears in 12+ files:

```typescript
const [data, setData] = useState(initialValue);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

// + manual cancellation via boolean flag, request ID ref, or signal object
```

**Files affected include:**
- `src/hooks/useNamespaceDiscovery.ts`
- `src/hooks/useNamespaceCapabilities.ts`
- `src/components/Scaling/hooks/useChartData.ts`
- `src/components/Scaling/hooks/useDeployments.ts`
- `src/components/Deployments/hooks/usePipelineRuns.ts`
- `src/components/DeployTab/hooks/useClusterDeployStatus.ts`
- `src/components/InfoTab/hooks/useInfoTab.ts`
- `src/components/GitHubPipeline/hooks/useDeploymentHealth.ts`
- And 4+ more

## Proposed Solution

1. Create a generic `useAsync` hook in `src/hooks/useAsync.ts` that:
- Manages `loading`, `error`, `data` state
- Uses request-ID-based cancellation (handles race conditions automatically)
- Supports `immediate` option (run on mount) and manual `execute()`
- Provides `reset()` to clear state
- Cleans up on unmount

2. Migrate 3-4 existing hooks as proof of concept:
- `useChartData` (uses `latestRequestIdRef` + `applyIfLatest` — maps directly)
- `useDeployments` (simple K8s API watcher)
- `usePipelineRuns` (signal object pattern)

3. Remaining hooks can be migrated incrementally in future PRs.

## Acceptance Criteria

- [ ] `useAsync` hook created with full test coverage (initial state, success, error, cancellation, reset, unmount cleanup)
- [ ] 3+ existing hooks migrated without behavior changes
- [ ] All existing tests pass
- [ ] Type check and lint pass

## Context

Part of the [codebase refactoring plan](docs/superpowers/plans/2026-03-25-codebase-refactoring.md) — Phase 1, PR 1.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.