@kellanjs/actioncraft
Version:
Fluent, type-safe builder for Next.js server actions.
47 lines • 1.68 kB
JavaScript
import { EXTERNAL_ERROR_TYPES } from "./types/errors.js";
import { err } from "./types/result.js";
/**
* Creates an appropriate initial state for any action based on its configuration.
* The initial state uses the action's real ID for consistency with actual results.
*
* For useActionState actions: returns StatefulApiResult with error and values
* For functional format actions: returns Result.err() with error
* For regular actions: returns ApiResult with error
*
* Usage:
* - useActionState: const [state, action] = useActionState(myAction, initial(myAction))
* - useState: const [state, setState] = useState(initial(myAction))
*/
export function initial(action) {
const error = {
type: EXTERNAL_ERROR_TYPES.INITIAL_STATE,
message: "Action has not been executed yet",
};
// Attempt to read the action ID created during craft()
const actionId =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
action?.__ac_id ?? "unknown";
// Attempt to read the Actioncraft config attached during craft()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cfg = action?.__ac_config;
// Functional format -> Result<_, _>
if (cfg?.resultFormat === "functional") {
return err(error, actionId);
}
// useActionState enabled -> StatefulApiResult
if (cfg?.useActionState) {
return {
success: false,
error,
values: undefined,
__ac_id: actionId,
};
}
// Default ApiResult shape
return {
success: false,
error,
__ac_id: actionId,
};
}
//# sourceMappingURL=initial.js.map