clear-react-router 2.1.2 → 2.1.4

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/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ [![npm version](https://badge.fury.io/js/clear-react-router.svg)](https://www.npmjs.com/package/clear-react-router)
2
+
1
3
  # Clear Router
2
4
 
3
5
  A lightweight, type-safe routing library for client side React applications with nested routes, data loading, navigation blocking, prefetching, and route actions.
@@ -12,7 +14,7 @@ It provides first-class support for:
12
14
 
13
15
  * Predictable routing
14
16
  * Built-in data loading
15
- * Route actions and forms
17
+ * Route actions
16
18
  * Simple, provider-free architecture
17
19
  * Small, explicit API
18
20
 
@@ -398,7 +400,7 @@ const routes = createRouter([
398
400
 
399
401
  Defines route-specific actions for handling data mutations such as creating, updating, or deleting resources.
400
402
 
401
- Actions are available through the `Form` component and the `useAction` hook. After a successful action, the current route is automatically invalidated, causing both `beforeLoad` and `loader` to run again in the background.
403
+ Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the current route is automatically invalidated, causing `loader` to run again in the background.
402
404
 
403
405
  ```tsx
404
406
  actions?: ({ context, params, invalidate, setContext }) => ({
@@ -414,77 +416,98 @@ actions?: ({ context, params, invalidate, setContext }) => ({
414
416
 
415
417
  #### Arguments
416
418
 
417
- | Property | Type | Description |
418
- | ------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------- |
419
- | `context` | `Record<string, unknown>` | Current router context. |
420
- | `params` | `Record<string, string>` | Route parameters. |
421
- | `invalidate` | `(path?: string) => Promise<void>` | Invalidates the current route or a specific route, re-running its `beforeLoad` and `loader`. |
422
- | `setContext` | `Dispatch<SetStateAction<Record<string, unknown>>>` | Updates the router context. |
419
+ ```ts
420
+ {
421
+ params: Record<string, string>; // Route parameters
422
+ context: Record<string, unknown>; // Router context
423
+ setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
424
+ searchParams: Record<string, string>; // URL search parameters
425
+ location: Location; // Route location
426
+ }
427
+ ```
423
428
 
424
429
  #### Returns
425
430
 
426
431
  A record where each key is an action name and each value is a function accepting a `FormData` instance.
427
432
 
428
- These action names are referenced by both `Form` and `useAction`.
429
-
430
- ```tsx
431
- <Form action="save" />
432
-
433
- const save = useAction('save');
434
- ```
433
+ ## useSubmitAction()
435
434
 
435
+ `useSubmitAction` wraps a route's `action` with submission state (`isSubmitting`, `data`, `error`) and gives you two ways to trigger it — a ready-made `onSubmit` for native forms, or a raw `submit(formData)` you can call from any form library.
436
436
 
437
- Actions can be executed declaratively with `<Form />` or imperatively with `useAction()`.
437
+ ```tsx
438
+ import { useSubmitAction } from 'clear-react-router';
438
439
 
439
- ## Form
440
+ const CreateUserForm = () => {
441
+ const { onSubmit, isSubmitting, error } = useSubmitAction('createUser');
440
442
 
441
- `Form` automatically creates a `FormData` object on submit event, executes the specified route action, invalidates the current route, and optionally resets the form, if fields are uncontrolled.
443
+ return (
444
+ <form onSubmit={onSubmit}>
445
+ <input name="email" disabled={isSubmitting} />
446
+ <button disabled={isSubmitting}>Create</button>
447
+ {error && <span>{error.message}</span>}
448
+ </form>
449
+ );
450
+ };
451
+ ```
442
452
 
443
- `isSubmitting` value available inside the `Form` component from the `useFormContext` hook
453
+ `submit(formData)` accepts a plain `FormData`, so it works with any form library that gives you
454
+ validated values — not just native `<form>` submissions:
444
455
 
445
456
  ```tsx
446
- import { Form, useFormContext } from 'clear-react-router';
457
+ import { useForm } from 'react-hook-form';
447
458
 
448
- const SubmitButton = () => {
449
- const {isSubmitting} = useFormContext()
450
- return <button disabled={isSubmitting} type='submit'>Save</button>
451
- }
459
+ const { register, handleSubmit } = useForm<FormValues>();
460
+ const { submit, isSubmitting } = useSubmitAction('createUser');
452
461
 
453
- <Form action="save" onSuccess={() => console.log('Saved')} onError={console.error}>
454
- <input name="title" />
455
- <SubmitButton />
456
- </Form>
462
+ const onValid = (values: FormValues) => {
463
+ const formData = new FormData();
464
+ Object.entries(values).forEach(([key, value]) => formData.append(key, String(value)));
465
+ return submit(formData);
466
+ };
457
467
 
468
+ <form onSubmit={handleSubmit(onValid)}>
469
+ <input {...register('email')} disabled={isSubmitting} />
470
+ </form>
458
471
  ```
459
472
 
460
- ### Props
461
-
462
- | Prop | Type | Description |
463
- | ----------- | --------------------------- | -------------------------------------------------------------------------------- |
464
- | `action` | `string` | Name of the route action to execute. |
465
- | `onSuccess` | `(result: unknown) => void` | Called when the action completes successfully. Receives the action return value. |
466
- | `onError` | `(error: unknown) => void` | Called when the action throws. |
467
- | `autoReset` | `boolean` | Automatically resets the form after a successful submission. Default: `true`. |
473
+ Arguments:
468
474
 
469
- During submission, `Form` exposes the current submission state through `useFormContext()`.
475
+ | Argument | Type | Default | Description |
476
+ |---|---|---|---|
477
+ | `action` | `string` | — | The action key defined in the route's `actions` |
478
+ | `options.onSuccess` | `(data: unknown) => void \| undefined` | `undefined` | Called after a successful submission |
479
+ | `options.onError` | `(error: unknown) => void \| undefined` | `undefined` | Called if the action throws |
480
+ | `options.autoReset` | `boolean \| undefined` | `true` | Reset the form element after a successful native submission (`onSubmit` only — has no effect on `submit`) |
481
+ | `options.withBeforeLoad` | `boolean \| undefined` | `false` | Whether to run the `beforeLoad` hook on a successful action submit as well |
470
482
 
471
- After a successful action:
483
+ Return value:
472
484
 
473
- * the current route is invalidated;
474
- * `beforeLoad` is executed again;
475
- * `loader` is executed again;
476
- * fresh loader data becomes available.
485
+ | Field | Type | Description |
486
+ |---|---|---|
487
+ | `submit` | `(formData: FormData) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
488
+ | `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
489
+ | `data` | `unknown` | Result of the last successful submission |
490
+ | `error` | `Error \| null` | Error from the last failed submission |
491
+ | `isSubmitting` | `boolean` | `true` while the action is in flight |
477
492
 
478
- ## useAction
493
+ ## useAction()
479
494
 
480
- `useAction` provides direct access to a route action without rendering a `<Form />`.
495
+ `useAction` provides direct access to a route action.
481
496
 
482
497
  ### Arguments
483
498
 
484
499
  | Argument | Type | Description |
485
500
  |----------|------|-------------|
486
501
  | `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
487
- | `options` | `{ onSuccess?, onError? }` | Optional callbacks invoked after the action succeeds or fails. |
502
+ | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails and `withBeforeLoad` value to set route's `beforeLoad` to run. |
503
+
504
+ ```ts
505
+ type Options = Partial<{
506
+ onSuccess: (args: unknown) => void;
507
+ onError: (args: unknown) => void;
508
+ withBeforeLoad?: boolean;
509
+ }> | undefined;
510
+ ```
488
511
 
489
512
  ```tsx
490
513
  const save = useAction('save');
@@ -498,7 +521,7 @@ const handleClick = async () => {
498
521
  <button onClick={handleClick}>Save</button>
499
522
  ```
500
523
 
501
- `useAction` automatically invalidates the current route after a successful action, causing both `beforeLoad` and `loader` to run again in the background.
524
+ `useAction` automatically invalidates the current route after a successful action, causing `loader` to run again in the background.
502
525
 
503
526
  This hook is useful when the mutation is triggered programmatically, such as from dialogs, context menus, drag-and-drop interactions, keyboard shortcuts, or custom UI components.
504
527
 
@@ -1 +1,4 @@
1
- export declare const useAction: (action: string, options?: import("../types").Options) => (arg: FormData) => Promise<void>;
1
+ export declare const useAction: (action: string, options?: import("../types").Options) => (arg: FormData) => Promise<{
2
+ data: unknown;
3
+ error: Error | null;
4
+ }>;
@@ -0,0 +1,18 @@
1
+ import { SubmitEvent } from 'react';
2
+ type Options = {
3
+ onSuccess?(arg: unknown): void;
4
+ onError?(arg: unknown): void;
5
+ autoReset?: boolean;
6
+ withBeforeLoad?: boolean;
7
+ };
8
+ export declare const useSubmitAction: (action: string, options?: Options) => {
9
+ submit: (formData: FormData) => Promise<{
10
+ data: unknown;
11
+ error: Error | null;
12
+ }>;
13
+ onSubmit: (evt: SubmitEvent<HTMLFormElement>) => Promise<void>;
14
+ data: unknown;
15
+ error: Error | null;
16
+ isSubmitting: boolean;
17
+ };
18
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  export { Router } from './components/Router';
2
2
  export { Link } from './components/Link';
3
- export { Form } from './components/Form';
4
3
  export { useNavigate } from './hooks/useNavigate';
5
4
  export { useParams } from './hooks/useParams';
6
5
  export { useLocation } from './hooks/useLocation';
@@ -11,7 +10,7 @@ export { useAction } from './hooks/useAction';
11
10
  export { useIsDataLoading } from './hooks/useIsDataLoading';
12
11
  export { useRouterContext } from './hooks/useRouterContext';
13
12
  export { useSearchParams } from './hooks/useSearchParams';
14
- export { useFormContext } from './hooks/useFormContext';
13
+ export { useSubmitAction } from './hooks/useSubmitAction';
15
14
  export { createRouter } from './utils/createRouter';
16
15
  export { lazy } from './utils/lazy';
17
16
  export type { RouteItem, BlockerState, Location, RouterProps, ElementProps } from './types';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Suspense, createContext, lazy as lazy$1, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
1
+ import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
2
  //#region \0rolldown/runtime.js
3
3
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
4
  //#endregion
@@ -536,24 +536,23 @@ var createRouterInstance = () => {
536
536
  const invalidate = createInvalidate(routerState, revalidateCache);
537
537
  const navigate = createNavigate(routerState, revalidateCache);
538
538
  const prefetch = createPrefetch(routerState, revalidateCache);
539
- const useGetAction = (actionKey) => {
540
- const { routeItem } = routerState.routeItemDataState.getState();
539
+ const useGetCurrentAction = (actionKey) => {
540
+ const { routeItem, location } = routerState.routeItemDataState.getState();
541
+ if (!routeItem) throw new Error("Route not found");
542
+ if (!routeItem.actions) throw new Error("Route action creator not found");
541
543
  const context = routerState.contextState.getState();
542
544
  const setContext = routerState.contextState.setState;
543
545
  const params = getParamsObject();
544
- if (!routeItem) throw new Error("Route not found");
545
- if (!routeItem.actions) throw new Error("Route action creator not found");
546
+ const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
546
547
  const action = routeItem.actions({
547
548
  context,
548
549
  setContext,
549
550
  params,
550
- invalidate
551
+ location,
552
+ searchParams
551
553
  })[actionKey];
552
554
  if (!action) throw new Error(`Action "${actionKey}" not found`);
553
- return {
554
- currentAction: action,
555
- invalidate
556
- };
555
+ return action;
557
556
  };
558
557
  return {
559
558
  state: routerState,
@@ -588,16 +587,23 @@ var createRouterInstance = () => {
588
587
  } else if (JSON.stringify(arg) !== JSON.stringify(location)) await navigate(arg);
589
588
  };
590
589
  },
591
- useGetAction,
592
590
  useAction: (action, options = {}) => {
593
- const { currentAction, invalidate } = useGetAction(action);
591
+ const currentAction = useGetCurrentAction(action);
594
592
  return async (formData) => {
595
593
  try {
596
- const result = await currentAction(formData);
597
- await invalidate();
598
- options.onSuccess?.(result);
594
+ const data = await currentAction(formData);
595
+ await invalidate("", { withBeforeLoad: options.withBeforeLoad });
596
+ options.onSuccess?.(data);
597
+ return {
598
+ data,
599
+ error: null
600
+ };
599
601
  } catch (error) {
600
602
  options.onError?.(error);
603
+ return {
604
+ data: null,
605
+ error
606
+ };
601
607
  }
602
608
  };
603
609
  }
@@ -914,42 +920,6 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
914
920
  });
915
921
  };
916
922
  //#endregion
917
- //#region context/FormContext.ts
918
- var FormContext = createContext({ isSubmitting: false });
919
- //#endregion
920
- //#region provider/FormProvider.tsx
921
- var FormProvider = ({ children, isSubmitting }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FormContext.Provider, {
922
- value: { isSubmitting },
923
- children
924
- });
925
- //#endregion
926
- //#region components/Form.tsx
927
- var Form = ({ children, action, onSuccess, onError, autoReset = true }) => {
928
- const { currentAction, invalidate } = router.hooks.useGetAction(action);
929
- const [isSubmitting, setIsSubmitting] = useState(false);
930
- const onSubmit = async (evt) => {
931
- evt.preventDefault();
932
- try {
933
- setIsSubmitting(true);
934
- const result = await currentAction(new FormData(evt.target));
935
- await invalidate();
936
- if (autoReset) evt.target.reset();
937
- onSuccess?.(result);
938
- } catch (error) {
939
- onError?.(error);
940
- } finally {
941
- setIsSubmitting(false);
942
- }
943
- };
944
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FormProvider, {
945
- isSubmitting,
946
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("form", {
947
- onSubmit,
948
- children
949
- })
950
- });
951
- };
952
- //#endregion
953
923
  //#region hooks/useParams.ts
954
924
  var useParams = router.hooks.useParams;
955
925
  //#endregion
@@ -1078,8 +1048,33 @@ var useSearchParams = () => {
1078
1048
  };
1079
1049
  };
1080
1050
  //#endregion
1081
- //#region hooks/useFormContext.ts
1082
- var useFormContext = () => useContext(FormContext);
1051
+ //#region hooks/useSubmitAction.ts
1052
+ var useSubmitAction = (action, options) => {
1053
+ const currentAction = router.hooks.useAction(action, options);
1054
+ const [data, setData] = useState();
1055
+ const [error, setError] = useState(null);
1056
+ const [isSubmitting, setIsSubmitting] = useState(false);
1057
+ const submit = useCallback(async (formData) => {
1058
+ setIsSubmitting(true);
1059
+ const result = await currentAction(formData);
1060
+ setIsSubmitting(false);
1061
+ setData(result.data);
1062
+ setError(result.error);
1063
+ return result;
1064
+ }, [currentAction]);
1065
+ return {
1066
+ submit,
1067
+ onSubmit: useCallback(async (evt) => {
1068
+ evt.preventDefault();
1069
+ const target = evt.target;
1070
+ const { error } = await submit(new FormData(target));
1071
+ if (!(options?.autoReset === false) && !error) target.reset();
1072
+ }, [options?.autoReset, submit]),
1073
+ data,
1074
+ error,
1075
+ isSubmitting
1076
+ };
1077
+ };
1083
1078
  //#endregion
1084
1079
  //#region utils/createLazyComponent.tsx
1085
1080
  var createLazyComponent = (importFn, fallback) => {
@@ -1119,4 +1114,4 @@ var lazy = (importFn) => ({
1119
1114
  importFn
1120
1115
  });
1121
1116
  //#endregion
1122
- export { Form, Link, Router, createRouter, lazy, useAction, useBlocker, useFormContext, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRouterContext, useSearchParams };
1117
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRouterContext, useSearchParams, useSubmitAction };
package/dist/types.d.ts CHANGED
@@ -9,25 +9,22 @@ export type LazyComponent = {
9
9
  }>;
10
10
  };
11
11
  export type RenderElement = (() => ReactElement) | ReactElement;
12
- export type BeforeLoad = (arg: {
12
+ type LoaderArgs = {
13
13
  context: Record<string, unknown>;
14
- redirect: (arg: Location | string) => Promise<void>;
15
14
  params: Record<string, string>;
16
15
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
17
16
  searchParams: Record<string, string>;
18
17
  location: Location;
18
+ };
19
+ export type BeforeLoad = (arg: LoaderArgs & {
20
+ redirect: (arg: Location | string) => Promise<void>;
19
21
  }) => Promise<unknown> | undefined | void;
20
22
  export type ScrollRestorationBehavior = 'auto' | 'smooth' | 'instant';
21
23
  export type ClientRouteItem = {
22
24
  path: string;
23
25
  element: RenderElement | LazyComponent;
24
- loader?(arg: {
25
- params: Record<string, string>;
26
- context: Record<string, unknown>;
27
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
28
- searchParams: Record<string, string>;
26
+ loader?(arg: LoaderArgs & {
29
27
  signal: AbortSignal;
30
- location: Location;
31
28
  }): Promise<unknown>;
32
29
  loaderFallback?: RenderElement;
33
30
  errorElement?: RenderElement;
@@ -46,12 +43,7 @@ export type ClientRouteItem = {
46
43
  params: Record<string, string>;
47
44
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
48
45
  }) => Promise<void>;
49
- actions?: (arg: {
50
- context: Record<string, unknown>;
51
- params: Record<string, string>;
52
- invalidate: (path?: string) => Promise<InvalidateResult[]>;
53
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
54
- }) => Record<string, (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown>;
46
+ actions?: (arg: LoaderArgs) => Record<string, (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown>;
55
47
  };
56
48
  export type RouteItem = ClientRouteItem & {
57
49
  element: RenderElement;
@@ -154,11 +146,10 @@ export type RouterType = {
154
146
  useLoaderState: <T>() => LoaderState<T>;
155
147
  useParams: <T>() => T;
156
148
  useNavigate: () => (arg: Location | string | -1) => Promise<void>;
157
- useGetAction: (actionKey: string) => {
158
- currentAction: (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown;
159
- invalidate: (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
160
- };
161
- useAction: (action: string, options?: Options) => (arg: FormData) => Promise<void>;
149
+ useAction: (action: string, options?: Options) => (arg: FormData) => Promise<{
150
+ data: unknown;
151
+ error: Error | null;
152
+ }>;
162
153
  };
163
154
  };
164
155
  export type InvalidateOptions = {
@@ -170,6 +161,7 @@ export type RevalidateCache = (args: RevalidateCacheArgs) => LoadingPromise;
170
161
  export type Options = Partial<{
171
162
  onSuccess: (args: unknown) => void;
172
163
  onError: (args: unknown) => void;
164
+ withBeforeLoad?: boolean;
173
165
  }> | undefined;
174
166
  export type InvalidateResult = {
175
167
  path: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.1.2",
3
+ "version": "2.1.4",
4
4
  "description": "A lightweight, type-safe routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
@@ -1,9 +0,0 @@
1
- import { PropsWithChildren } from 'react';
2
- type FormProps = {
3
- action: string;
4
- onSuccess?(arg: unknown): void;
5
- onError?(arg: unknown): void;
6
- autoReset?: boolean;
7
- };
8
- export declare const Form: ({ children, action, onSuccess, onError, autoReset }: PropsWithChildren<FormProps>) => import("react/jsx-runtime").JSX.Element;
9
- export {};
@@ -1,4 +0,0 @@
1
- export type FormContextProps = {
2
- isSubmitting: boolean;
3
- };
4
- export declare const FormContext: import("react").Context<FormContextProps>;
@@ -1 +0,0 @@
1
- export declare const useFormContext: () => import("../context/FormContext").FormContextProps;
@@ -1,3 +0,0 @@
1
- import { PropsWithChildren } from 'react';
2
- import { FormContextProps } from '../context/FormContext';
3
- export declare const FormProvider: ({ children, isSubmitting }: PropsWithChildren<FormContextProps>) => import("react/jsx-runtime").JSX.Element;