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 status property of the localState.
  • Optionally sets a message if provided.
  • Optionally updates the data property with new values.
  • Works with types defined in a shared API state interface.

DEV STRATEGIES

  1. 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.
  1. 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.
  1. DEFAULT BEHAVIOR
FeatureDefaultDescription
statusrequiredUpdates the status to reflect the current API state.
messageoptionalSets a message to provide context (e.g., errors, success feedback).
dataoptionalAdds or replaces response data in the API state object.
mutabilityin placeThe localState object is directly modified (no immutability enforcement).

FLOW SUMMARY

  • Takes in a current state object (APIState) and a new State value.
  • Optionally updates the message and data fields if values are provided.
  • Intended to be used across API service handlers and Vue components for consistency.

Copyright © 2026