axokit-react 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aakarsh Chaudhary
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # AxoKit — AsyncButton & useAsyncAction
2
+
3
+ A tiny headless React UI primitive for handling asynchronous button states.
4
+
5
+ Package name: `@axokit/react` (install with `npm install @axokit/react`).
6
+
7
+ ## Features
8
+
9
+ - Automatic loading / success / error states
10
+ - Hook (`useAsyncAction`) and headless component
11
+ - TypeScript support
12
+ - Minimal styles; load your own CSS or Tailwind classes
13
+ - Works with React 18+
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @axokit/react
19
+ # also install peer dependencies
20
+ npm install react react-dom
21
+ ```
22
+
23
+ ## Usage (component)
24
+
25
+ ```tsx
26
+ import { AsyncButton } from '@axokit/react';
27
+
28
+ function SaveButton() {
29
+ const save = () => fetch('/api/save', { method: 'POST' });
30
+
31
+ return (
32
+ <AsyncButton
33
+ onAction={save}
34
+ loadingText="Saving..."
35
+ successText="Saved ✓"
36
+ errorText="Try again"
37
+ disableOnSuccess={false} // optional
38
+ className="px-4 py-2 rounded bg-blue-600 text-white"
39
+ >
40
+ Save
41
+ </AsyncButton>
42
+ );
43
+ }
44
+ ```
45
+
46
+ ## Usage (hook)
47
+
48
+ ```tsx
49
+ import { useAsyncAction } from '@axokit/react';
50
+
51
+ function HookExample() {
52
+ const save = () => fetch('/api/save', { method: 'POST' });
53
+ const { state, trigger, reset } = useAsyncAction(save);
54
+
55
+ return (
56
+ <div>
57
+ <button onClick={trigger} disabled={state === 'loading'}>
58
+ {state === 'loading' ? 'Saving…' : state === 'success' ? 'Saved' : 'Save'}
59
+ </button>
60
+ <button onClick={reset}>Reset</button>
61
+ </div>
62
+ );
63
+ }
64
+ ```
65
+
66
+ ## API
67
+
68
+ ### `AsyncButton(props)`
69
+
70
+ - `onAction: () => Promise<any>` — **required**.
71
+ - `loadingText?: string` — default: `"Loading..."`.
72
+ - `successText?: string` — default: `"Done!"`.
73
+ - `errorText?: string` — default: `"Try again"`.
74
+ - `successDuration?: number` — default: `1200` ms.
75
+ - `errorDuration?: number` — default: `3000` ms.
76
+ - `disableOnSuccess?: boolean` — default: `true`.
77
+ - `onSuccess?: () => void`.
78
+ - `onActionError?: (error: Error) => void`.
79
+ - All other native `button` props are forwarded.
80
+
81
+ ### `useAsyncAction(action, options?)`
82
+
83
+ Returns `{ state, error, trigger, reset }` with state `'idle'|'loading'|'success'|'error'`.
84
+
85
+ ## Accessibility
86
+
87
+ - Button sets `aria-busy` while loading.
88
+ - Exposes `data-state` attribute for styling.
89
+ - The hook returns state for building your own live regions.
90
+
91
+ ## Styling
92
+
93
+ Use `data-state` to adjust styles via CSS/Tailwind.
94
+
95
+ ```css
96
+ .btn { @apply px-4 py-2 rounded; }
97
+ .btn[data-state="loading"] { opacity: 0.7; }
98
+ .btn[data-state="success"] { background-color: theme(colors.green.600); }
99
+ .btn[data-state="error"] { background-color: theme(colors.red.600); }
100
+ ```
101
+
102
+ ## License
103
+
104
+ MIT
105
+
106
+ This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
107
+
108
+ ## Learn More
109
+
110
+ To learn more about Next.js, take a look at the following resources:
111
+
112
+ - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
113
+ - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
114
+
115
+ You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
116
+
117
+ ## Deploy on Vercel
118
+
119
+ The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
120
+
121
+ Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
@@ -0,0 +1,32 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import * as React from 'react';
3
+
4
+ type AsyncState = 'idle' | 'loading' | 'success' | 'error';
5
+ interface UseAsyncActionOptions {
6
+ successDuration?: number;
7
+ errorDuration?: number;
8
+ onSuccess?: () => void;
9
+ onActionError?: (error: Error) => void;
10
+ }
11
+ interface UseAsyncActionReturn {
12
+ state: AsyncState;
13
+ error: Error | null;
14
+ trigger: () => Promise<void>;
15
+ reset: () => void;
16
+ }
17
+ declare function useAsyncAction(action: () => Promise<any>, options?: UseAsyncActionOptions): UseAsyncActionReturn;
18
+ interface AsyncButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
19
+ onAction: () => Promise<any>;
20
+ loadingText?: string;
21
+ successText?: string;
22
+ errorText?: string;
23
+ successDuration?: number;
24
+ errorDuration?: number;
25
+ onSuccess?: () => void;
26
+ onActionError?: (error: Error) => void;
27
+ disableOnSuccess?: boolean;
28
+ children: React.ReactNode;
29
+ }
30
+ declare function AsyncButton({ onAction, loadingText, successText, errorText, successDuration, errorDuration, onSuccess, onActionError, disableOnSuccess, children, disabled, className, ...props }: AsyncButtonProps): react_jsx_runtime.JSX.Element;
31
+
32
+ export { AsyncButton, useAsyncAction };
package/dist/index.js ADDED
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AsyncButton: () => AsyncButton,
34
+ useAsyncAction: () => useAsyncAction
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // src/AsyncButton.tsx
39
+ var React = __toESM(require("react"));
40
+ var import_jsx_runtime = require("react/jsx-runtime");
41
+ function useAsyncAction(action, options = {}) {
42
+ const { successDuration = 1200, errorDuration = 3e3, onSuccess, onActionError } = options;
43
+ const [state, setState] = React.useState("idle");
44
+ const [error, setError] = React.useState(null);
45
+ const timeoutRef = React.useRef(null);
46
+ const mountedRef = React.useRef(true);
47
+ React.useEffect(() => {
48
+ return () => {
49
+ mountedRef.current = false;
50
+ if (timeoutRef.current) {
51
+ clearTimeout(timeoutRef.current);
52
+ timeoutRef.current = null;
53
+ }
54
+ };
55
+ }, []);
56
+ const reset = () => {
57
+ if (timeoutRef.current) {
58
+ clearTimeout(timeoutRef.current);
59
+ timeoutRef.current = null;
60
+ }
61
+ if (!mountedRef.current)
62
+ return;
63
+ setState("idle");
64
+ setError(null);
65
+ };
66
+ const trigger = async () => {
67
+ if (state === "loading")
68
+ return;
69
+ if (timeoutRef.current) {
70
+ clearTimeout(timeoutRef.current);
71
+ timeoutRef.current = null;
72
+ }
73
+ if (mountedRef.current) {
74
+ setState("loading");
75
+ setError(null);
76
+ }
77
+ try {
78
+ await action();
79
+ if (!mountedRef.current)
80
+ return;
81
+ setState("success");
82
+ onSuccess?.();
83
+ timeoutRef.current = setTimeout(() => {
84
+ if (mountedRef.current)
85
+ setState("idle");
86
+ }, successDuration);
87
+ } catch (err) {
88
+ const error2 = err instanceof Error ? err : new Error("Action failed");
89
+ if (mountedRef.current) {
90
+ setError(error2);
91
+ setState("error");
92
+ onActionError?.(error2);
93
+ }
94
+ timeoutRef.current = setTimeout(() => {
95
+ if (mountedRef.current)
96
+ setState("idle");
97
+ }, errorDuration);
98
+ }
99
+ };
100
+ return { state, error, trigger, reset };
101
+ }
102
+ function AsyncButton({
103
+ onAction,
104
+ loadingText = "Loading...",
105
+ successText = "Done!",
106
+ errorText = "Try again",
107
+ successDuration = 1200,
108
+ errorDuration = 3e3,
109
+ onSuccess,
110
+ onActionError,
111
+ disableOnSuccess = true,
112
+ children,
113
+ disabled,
114
+ className = "",
115
+ ...props
116
+ }) {
117
+ const { state, trigger } = useAsyncAction(onAction, {
118
+ successDuration,
119
+ errorDuration,
120
+ onSuccess,
121
+ onActionError
122
+ });
123
+ const getLabel = () => {
124
+ switch (state) {
125
+ case "loading":
126
+ return loadingText;
127
+ case "success":
128
+ return successText;
129
+ case "error":
130
+ return errorText;
131
+ default:
132
+ return children;
133
+ }
134
+ };
135
+ const isDisabled = disabled || state === "loading" || state === "success" && disableOnSuccess;
136
+ const { onClick: _nativeOnClick, type: buttonType = "button", ...rest } = props;
137
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
138
+ "button",
139
+ {
140
+ type: buttonType,
141
+ ...rest,
142
+ className,
143
+ onClick: trigger,
144
+ disabled: isDisabled,
145
+ "aria-busy": state === "loading",
146
+ "data-state": state,
147
+ children: getLabel()
148
+ }
149
+ );
150
+ }
151
+ // Annotate the CommonJS export names for ESM import in node:
152
+ 0 && (module.exports = {
153
+ AsyncButton,
154
+ useAsyncAction
155
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,117 @@
1
+ // src/AsyncButton.tsx
2
+ import * as React from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ function useAsyncAction(action, options = {}) {
5
+ const { successDuration = 1200, errorDuration = 3e3, onSuccess, onActionError } = options;
6
+ const [state, setState] = React.useState("idle");
7
+ const [error, setError] = React.useState(null);
8
+ const timeoutRef = React.useRef(null);
9
+ const mountedRef = React.useRef(true);
10
+ React.useEffect(() => {
11
+ return () => {
12
+ mountedRef.current = false;
13
+ if (timeoutRef.current) {
14
+ clearTimeout(timeoutRef.current);
15
+ timeoutRef.current = null;
16
+ }
17
+ };
18
+ }, []);
19
+ const reset = () => {
20
+ if (timeoutRef.current) {
21
+ clearTimeout(timeoutRef.current);
22
+ timeoutRef.current = null;
23
+ }
24
+ if (!mountedRef.current)
25
+ return;
26
+ setState("idle");
27
+ setError(null);
28
+ };
29
+ const trigger = async () => {
30
+ if (state === "loading")
31
+ return;
32
+ if (timeoutRef.current) {
33
+ clearTimeout(timeoutRef.current);
34
+ timeoutRef.current = null;
35
+ }
36
+ if (mountedRef.current) {
37
+ setState("loading");
38
+ setError(null);
39
+ }
40
+ try {
41
+ await action();
42
+ if (!mountedRef.current)
43
+ return;
44
+ setState("success");
45
+ onSuccess?.();
46
+ timeoutRef.current = setTimeout(() => {
47
+ if (mountedRef.current)
48
+ setState("idle");
49
+ }, successDuration);
50
+ } catch (err) {
51
+ const error2 = err instanceof Error ? err : new Error("Action failed");
52
+ if (mountedRef.current) {
53
+ setError(error2);
54
+ setState("error");
55
+ onActionError?.(error2);
56
+ }
57
+ timeoutRef.current = setTimeout(() => {
58
+ if (mountedRef.current)
59
+ setState("idle");
60
+ }, errorDuration);
61
+ }
62
+ };
63
+ return { state, error, trigger, reset };
64
+ }
65
+ function AsyncButton({
66
+ onAction,
67
+ loadingText = "Loading...",
68
+ successText = "Done!",
69
+ errorText = "Try again",
70
+ successDuration = 1200,
71
+ errorDuration = 3e3,
72
+ onSuccess,
73
+ onActionError,
74
+ disableOnSuccess = true,
75
+ children,
76
+ disabled,
77
+ className = "",
78
+ ...props
79
+ }) {
80
+ const { state, trigger } = useAsyncAction(onAction, {
81
+ successDuration,
82
+ errorDuration,
83
+ onSuccess,
84
+ onActionError
85
+ });
86
+ const getLabel = () => {
87
+ switch (state) {
88
+ case "loading":
89
+ return loadingText;
90
+ case "success":
91
+ return successText;
92
+ case "error":
93
+ return errorText;
94
+ default:
95
+ return children;
96
+ }
97
+ };
98
+ const isDisabled = disabled || state === "loading" || state === "success" && disableOnSuccess;
99
+ const { onClick: _nativeOnClick, type: buttonType = "button", ...rest } = props;
100
+ return /* @__PURE__ */ jsx(
101
+ "button",
102
+ {
103
+ type: buttonType,
104
+ ...rest,
105
+ className,
106
+ onClick: trigger,
107
+ disabled: isDisabled,
108
+ "aria-busy": state === "loading",
109
+ "data-state": state,
110
+ children: getLabel()
111
+ }
112
+ );
113
+ }
114
+ export {
115
+ AsyncButton,
116
+ useAsyncAction
117
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "axokit-react",
3
+ "version": "0.0.1",
4
+ "description": "Headless async button and hook for React",
5
+ "main": "dist/index.cjs.js",
6
+ "module": "dist/index.esm.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "author": "Aakarsh Chaudhary <aakarsh0219@gmail.com>",
12
+ "license": "MIT",
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "peerDependencies": {
17
+ "react": ">=18",
18
+ "react-dom": ">=18"
19
+ },
20
+ "devDependencies": {
21
+ "typescript": "^5.0.0",
22
+ "tsup": "^6.0.0",
23
+ "eslint": "^8.0.0",
24
+ "prettier": "^3.0.0",
25
+ "@types/react": "^18.0.0",
26
+ "@types/react-dom": "^18.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup src/index.ts --dts --format cjs,esm --clean",
30
+ "lint": "eslint \"src/**/*.{ts,tsx}\"",
31
+ "format": "prettier --write \"src/**/*.{ts,tsx,js,json,md}\"",
32
+ "prepare": "npm run build"
33
+ }
34
+ }