Data Handling
Fetching, transforming, and displaying data
Data Handling & API Integration
Handling data involves three steps: Fetching, Transforming, and Displaying.
In mobileLauncherStandard, we use Redux Toolkit Query (RTK Query) because it handles caching, loading states, and offline persistence for us.
The Data Flow
- API Definition: Define endpoints (URLs).
- Hook Generation: RTK Query auto-generates hooks like
useGetTodosQuery. - Component Usage: Use the hook in your UI.
Real World Example: Todos API
Located at src/features/todos/api/todos-api.ts. This file defines how we talk to the backend.
1. Fetching Data (Query)
// src/features/todos/api/todos-api.ts
getTodosSummary: builder.query<TodoSummary[], TodoListParams | undefined>({
// The 'queryFn' performs the actual async fetch
queryFn: async (params = {}) => {
try {
// Call the service layer (separation of concerns)
const data = await todosApiService.getTodosSummary(params);
return { data };
} catch (error) {
return { error: error.message };
}
},
// Cache tags for automatic invalidation (refetching)
providesTags: ['Todo'],
});2. Transforming Data (map/filter)
Often the raw API data isn't exactly what the UI needs. We use JavaScript array methods to transform it.
// Common pattern in components
const { data: todos } = useGetTodosSummaryQuery();
// Filter: Show only incomplete tasks
const activeTodos = todos?.filter(todo => !todo.completed);
// Map: Transform for display
const viewModels = activeTodos?.map(todo => ({
id: todo.id,
title: todo.title.toUpperCase(), // Transform
isOverdue: new Date(todo.deadline) < new Date(), // Computed property
}));3. Displaying Data (JSON)
JSON (JavaScript Object Notation) is the language of APIs.
Key Rule: Always inspect your JSON structure.
If the API returns { "data": [ ... ] }, you must access response.data.
TypeScript to the Rescue
We define precise shapes for our data in src/features/todos/types/index.ts.
export interface TodoSummary {
id: string;
title: string;
completed: boolean;
deadline: string; // ISO Date string
}This ensures we never try to access todo.nme (typo) instead of todo.name.
Common JS Methods You Need
.map(): Transform items.[1, 2] -> [2, 4].filter(): Remove items.[1, 2, 3] -> [1, 3].find(): Get one item.[id:1, id:2] -> id:1.reduce(): Summarize.[1, 2, 3] -> 6