### useUserInfo - React Authentication Hook
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
A React hook for managing user authentication state. It includes automatic refetch control and query caching for user information. Dependencies include authentication API functions.
```typescript
import { useUserInfo, useLogout } from './src/api/auth';
function UserProfile() {
const { data: userInfo, isLoading, error } = useUserInfo();
const logout = useLogout();
if (isLoading) return
Loading user info...
;
if (error) return
Authentication error
;
return (
User Profile
ID: {userInfo.id}
Email: {userInfo.email}
);
}
// Usage in component with conditional rendering
function ProtectedContent() {
const { data: user, isLoading } = useUserInfo();
if (isLoading) return null;
if (!user?.id) {
// User will be automatically redirected to login
return
Redirecting to login...
;
}
return
Welcome, {user.email}!
;
}
```
--------------------------------
### AidboxCall - Simplified JSON API Requests
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
AidboxCall is a higher-level API wrapper that simplifies common CRUD operations by automatically handling JSON serialization and deserialization, providing typed responses.
```APIDOC
## AidboxCall - Simplified JSON API Requests
### Description
A higher-level API wrapper that automatically handles JSON serialization/deserialization for simplified CRUD operations and typed responses.
### Method
Any valid HTTP method (GET, POST, PUT, DELETE, etc.)
### Endpoint
`/fhir/*` (and other Aidbox API endpoints)
### Parameters
#### Path Parameters
None specific to AidboxCall itself, depends on the endpoint.
#### Query Parameters
- **params** (object) - Optional - Query parameters to append to the URL.
#### Request Body
- **method** (string) - Required - The HTTP method for the request.
- **url** (string) - Required - The endpoint URL.
- **body** (object | string) - Optional - The request body, can be an object or a JSON string.
### Request Example
```typescript
import { AidboxCall } from './src/api/auth';
interface Patient { resourceType: 'Patient'; id: string; name: Array<{ given: string[]; family: string; }>; birthDate: string; }
const patient = await AidboxCall({ method: 'GET', url: '/fhir/Patient/patient-456' });
const newPatient = await AidboxCall({
method: 'POST',
url: '/fhir/Patient',
body: {
resourceType: 'Patient',
name: [{ given: ['John'], family: 'Doe' }],
birthDate: '1990-01-01',
gender: 'male'
}
});
const searchResults = await AidboxCall({
method: 'GET',
url: '/fhir/Patient',
params: { name: 'Doe', birthdate: 'gt1980-01-01', _count: '10', _sort: '-birthdate' }
});
```
### Response
#### Success Response (200)
- The response body is automatically deserialized into the specified generic type (or `any` if not specified).
#### Response Example
```json
{
"resourceType": "Patient",
"id": "patient-456",
"name": [
{
"given": ["Jane"],
"family": "Doe"
}
],
"birthDate": "1995-05-15"
}
```
```
--------------------------------
### Transform FHIR Schema Snapshot to Tree - TypeScript
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
Transforms FHIR resource schema snapshots into hierarchical tree structures suitable for navigation and visualization. It takes an array of schema objects and returns a map representing the tree. Dependencies include the `transformSnapshotToTree` function from `./src/utils`.
```typescript
import { transformSnapshotToTree } from './src/utils';
// FHIR Patient schema snapshot data
const snapshotData = [
{ type: 'root', name: 'Patient', path: 'Patient', short: 'Information about an individual' },
{ type: 'complex', path: 'Patient.identifier', name: 'identifier', datatype: 'Identifier', min: 0, max: '*', short: 'An identifier for this patient' },
{ type: 'primitive', path: 'Patient.active', name: 'active', datatype: 'boolean', min: 0, max: '1', short: 'Whether this patient's record is in active use' },
{ type: 'complex', path: 'Patient.name', name: 'name', datatype: 'HumanName', min: 0, max: '*', short: 'A name associated with the patient', flags: ['summary'] },
{ type: 'primitive', path: 'Patient.name.family', name: 'family', datatype: 'string', min: 0, max: '1', short: 'Family name' },
{ type: 'primitive', path: 'Patient.name.given', name: 'given', datatype: 'string', min: 0, max: '*', short: 'Given names' }
];
const tree = transformSnapshotToTree(snapshotData);
// Tree structure with hierarchical relationships
console.log(tree['root']);
// { name: 'Root', children: ['Patient'] }
console.log(tree['Patient']);
// {
// name: 'Patient',
// meta: {
// type: 'Resource',
// min: '0',
// max: '*',
// description: 'Information about an individual'
// },
// children: ['Patient.identifier', 'Patient.active', 'Patient.name']
// }
console.log(tree['Patient.name']);
// {
// name: 'name',
// meta: {
// type: 'HumanName',
// min: '0',
// max: '*',
// short: 'A name associated with the patient',
// description: 'A name associated with the patient',
// isSummary: true
// },
// children: ['Patient.name.family', 'Patient.name.given']
// }
console.log(tree['Patient.name.given']);
// {
// name: 'given',
// meta: {
// type: 'string',
// min: '0',
// max: '*',
// short: 'Given names',
// description: 'Given names',
// lastNode: true // Indicates leaf node
// }
// }
// Use tree for navigation UI
function renderTree(nodeId: string) {
const node = tree[nodeId];
return (
);
}
// The hook automatically fetches last 100 HTTP-type history entries
// Sorted by _lastUpdated in descending order
// Stale time: 30 seconds (won't refetch if data is fresh)
```
--------------------------------
### Retrieve Aidbox Base URL - TypeScript
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
Retrieves the Aidbox server base URL by checking cookies, environment variables, or defaulting to the current window's location. This utility is crucial for configuring API requests. Dependencies include the `getAidboxBaseURL` function from `./src/utils`.
```typescript
import { getAidboxBaseURL } from './src/utils';
// Get base URL for API requests
const baseURL = getAidboxBaseURL();
console.log(baseURL); // 'https://my-aidbox.instance.com' or 'http://localhost:8080'
// Priority order:
// 1. Cookie: 'aidbox-base-url'
// 2. Environment variable: VITE_AIDBOX_BASE_URL
// 3. Current window location
// Use in custom API calls
async function customRequest(endpoint: string) {
const url = `${getAidboxBaseURL()}${endpoint}`;
const response = await fetch(url, {
credentials: 'include',
headers: { 'Content-Type': 'application/json' }
});
return response.json();
}
// Set base URL via cookie (typically done by backend)
document.cookie = `aidbox-base-url=${encodeURIComponent('https://custom.aidbox.app')}; path=/`;
```
--------------------------------
### useDebounce - React Debounce Hook
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
A custom React hook for debouncing rapid function calls. It is ideal for search inputs and API calls triggered by user input, delaying execution until a specified time has passed without new calls.
```typescript
import { useDebounce } from './src/hooks/useDebounce';
import { useState } from 'react';
function PatientSearch() {
const [results, setResults] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
// Debounce search API call by 500ms
const debouncedSearch = useDebounce(async (term: string) => {
if (term.length < 2) {
setResults([]);
return;
}
const response = await AidboxCall({
method: 'GET',
url: '/fhir/Patient',
params: { name: term, _count: '20' }
});
setResults(response.entry || []);
}, 500);
const handleSearchChange = (e: React.ChangeEvent) => {
const value = e.target.value;
setSearchTerm(value);
debouncedSearch(value); // API call delayed until typing stops
};
return (
{results.map(patient => (
{patient.resource.name?.[0]?.family}
))}
);
}
```
--------------------------------
### FHIR Resource CRUD Operations
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
Provides functions for creating, reading, updating, deleting, and fetching the history of FHIR resources. It ensures consistent error handling and type safety for all operations.
```typescript
import {
fetchResource,
createResource,
updateResource,
deleteResource,
fetchResourceHistory
} from './src/components/ResourceEditor/api';
// Fetch a single resource
const observation = await fetchResource('Observation', 'obs-789');
console.log(observation.resourceType); // 'Observation'
// Create a new resource
const newCondition = await createResource('Condition', {
resourceType: 'Condition',
clinicalStatus: {
coding: [{
system: 'http://terminology.hl7.org/CodeSystem/condition-clinical',
code: 'active'
}]
},
code: {
coding: [{
system: 'http://snomed.org/sct',
code: '73211009',
display: 'Diabetes mellitus'
}]
},
subject: {
reference: 'Patient/patient-123'
}
});
console.log(newCondition.id); // Auto-generated ID
// Update existing resource
const updatedCondition = await updateResource('Condition', newCondition.id, {
...newCondition,
clinicalStatus: {
coding: [{
system: 'http://terminology.hl7.org/CodeSystem/condition-clinical',
code: 'resolved'
}]
},
abatementDateTime: '2024-01-15T10:30:00Z'
});
// Fetch resource history (version timeline)
const history = await fetchResourceHistory('Condition', newCondition.id);
console.log(history.total); // Number of versions
history.entry.forEach(entry => {
console.log(`Version ${entry.resource.meta.versionId}: ${entry.resource.meta.lastUpdated}`);
});
// Delete resource
await deleteResource('Condition', newCondition.id);
```
--------------------------------
### useLocalStorage Hook: React Persistent State with Cross-Tab Sync
Source: https://context7.com/healthsamurai/aidbox-ui/llms.txt
A React hook for managing state persisted in localStorage. It supports basic string storage, complex object storage with type safety, and synchronization across browser tabs. Custom serialization and deserialization functions can also be provided.
```typescript
import { useLocalStorage } from './src/hooks/useLocalStorage';
function ThemeSettings() {
// Basic usage with string
const [theme, setTheme, removeTheme] = useLocalStorage({
key: 'app-theme',
defaultValue: 'light'
});
return (