Task: Implement a custom React hook and wire UI interactions
Context
You are working in a React app that already includes a basic API module and a simple UI scaffold (a page with a list and a modal placeholder). Your goal is to:
-
Create a reusable custom hook that fetches data via the provided API, transforms it, and exposes loading/error states.
-
Update the UI so that a modal can open/close, a list can expand/collapse, and multiple buttons perform simple, specified actions.
Assume the starter code includes an API function (for example, api.getItems) that returns a promise resolving to an array of raw items. If your scaffold names the function differently, use that instead. You may design the data transformation either by passing a transform function to the hook or by hard-coding a simple transform inside the component for demonstration.
Requirements
-
Custom hook
-
Implement a hook (e.g.,
useApiData
) for function components that:
-
Calls the provided API function on mount (and when dependencies change) using
useEffect
with an inner async function.
-
Transforms the returned data into a different format (via a
transform
function argument or an internal mapping).
-
Returns
{ data, loading, error }
and also a
refetch
function.
-
Handles errors and toggles
loading
correctly.
-
Guards against setting state on unmounted components (e.g., via an isMounted flag or
AbortController
).
-
UI interactions
-
Add state and handlers to:
-
Open and close a modal.
-
Expand and collapse a list.
-
Provide several buttons that perform simple actions.
-
Wire everything to component state and the hook.
-
Buttons to implement (minimum)
-
Refresh Data: triggers a refetch using the hook.
-
Clear Error: clears any current error state exposed by the hook.
-
Increment Counter: increments a local counter displayed in the UI.
-
Toggle List: expands/collapses the list content.
-
Display behavior
-
Show loading and error states near the list.
-
When the list is collapsed, show a summary (e.g., 'N items hidden'). When expanded, render the items.
-
Modal should be visible only when open, and provide an in-modal Close action.
-
Constraints
-
Use React function components and Hooks only.
-
Use
useEffect
with an inner async function (the effect callback itself should not be async).
-
Keep the hook reusable and decoupled from specific endpoints as much as possible.
What to deliver
-
The custom hook implementation.
-
The updated component(s) showing the modal, collapsible list, and buttons with wired behavior.
-
Minimal notes or comments explaining how to run/refetch and how the transform works.