Composables
useStateModifier
Description
The useStateModifier composable provides a utility function for updating an APIState object in a consistent and type-safe manner. It is designed to streamline state management for API calls by handling status, messages, and optional data updates in one call.
FEATURE GOALS
- Simplify updating API response state in a clean and reusable way.
- Improve code consistency when handling API status transitions.
- Reduce boilerplate logic in components and services.
FEATURE EXPECTATIONS
- Updates the
statusproperty of thelocalState. - Optionally sets a
messageif provided. - Optionally updates the
dataproperty with new values. - Works with types defined in a shared API state interface.
DEV STRATEGIES
- Composables Logic
useStateModifier(apiState, "success", "Data loaded successfully", responseData);
- Updates apiState.status to "success".
- Sets a success message.
- Injects the latest API data into the state.
- Implementation
export const useScrollToElement = (element: HTMLElement, opts: object = {}) => {
import type { APIState, State } from "~/types/api-state.type";
export const useStateModifier = (
localState: APIState,
newState: State,
newStateMessage?: string,
newData?: object
) => {
localState.status = newState;
if (typeof newStateMessage === "string") {
localState.message = newStateMessage;
}
if (newData) {
localState.data = newData;
}
};
- Directly mutates the passed localState object.
- Ensures optional arguments (message, data) are conditionally applied.
- DEFAULT BEHAVIOR
| Feature | Default | Description |
|---|---|---|
status | required | Updates the status to reflect the current API state. |
message | optional | Sets a message to provide context (e.g., errors, success feedback). |
data | optional | Adds or replaces response data in the API state object. |
mutability | in place | The localState object is directly modified (no immutability enforcement). |
FLOW SUMMARY
- Takes in a current state object (
APIState) and a newStatevalue. - Optionally updates the
messageanddatafields if values are provided. - Intended to be used across API service handlers and Vue components for consistency.