clear-react-router 2.2.1 → 2.2.3

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
@@ -73,23 +73,21 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
73
73
  | `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
74
74
  | `beforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
75
75
  | `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
76
- | `afterLoad` | `({ params, context, setContext }) => Promise<void>` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
76
+ | `afterLoad` | `({ params, context, searchParams }) => Promise<void> \| void` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
77
77
  | `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
78
78
  | `fallback` | `ReactElement \| () => ReactElement` | Loading fallback (for lazy loading) |
79
- | `loaderFallback` | `ReactElement \| () => ReactElement` | Loading fallback for the route's `loader`. Overrides the global `defaultLoaderFallback` set in `Router` |
79
+ | `loaderFallback` | `ReactElement \| () => ReactElement` | Loading fallback for the route's `loader`. Overrides the global `Router.defaultLoaderFallback` |
80
80
  | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
81
81
  | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
82
- | `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `defaultErrorElement` set in `Router` |
82
+ | `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
83
83
  | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
84
84
  | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
85
- | `actions` | `({ params, context, invalidate, setContext }) => Record<string, (formData: FormData) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. Actions receive `FormData`, can update context via `setContext`, and can invalidate cached loader data using the router-provided `invalidate` |
85
+ | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
86
86
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
87
87
  | `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
88
88
  | `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
89
89
 
90
- Before load arguments (see [`redirect`](#redirect) for details on programmatic redirects):
91
-
92
- `beforeLoad` and `loader` both receive:
90
+ `beforeLoad`, `loader` and `actions` receive:
93
91
 
94
92
  ```ts
95
93
  {
@@ -100,13 +98,15 @@ Before load arguments (see [`redirect`](#redirect) for details on programmatic r
100
98
  location: Location; // Route location
101
99
  }
102
100
  ```
103
-
101
+ see [`Location`](#uselocation) and [`Where you came from`](#where-you-came-from) for type details
102
+
104
103
  `beforeLoad` additionally receives:
105
104
  ```ts
106
105
  {
107
106
  redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
108
107
  }
109
108
  ```
109
+ see [`redirect`](#redirect) for details on programmatic redirects
110
110
 
111
111
  `loader` additionally receives:
112
112
  ```ts
@@ -405,14 +405,9 @@ Defines route-specific actions for handling data mutations such as creating, upd
405
405
  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.
406
406
 
407
407
  ```tsx
408
- actions?: ({ context, params, invalidate, setContext }) => ({
409
- save: async (formData) => {
410
- await api.updatePost(params.id, formData);
411
- },
412
-
413
- remove: async () => {
414
- await api.deletePost(params.id);
415
- },
408
+ actions?: ({ params, context, searchParams, setContext, location }) => ({
409
+ save: async (data: Record<string, unknown>) => await api.updatePost(params.id, data),
410
+ remove: async () => await api.deletePost(params.id),
416
411
  })
417
412
  ```
418
413
 
@@ -430,11 +425,11 @@ actions?: ({ context, params, invalidate, setContext }) => ({
430
425
 
431
426
  #### Returns
432
427
 
433
- A record where each key is an action name and each value is a function accepting a `FormData` instance.
428
+ A record where each key is an action name and each value is a function accepting an object data argument.
434
429
 
435
430
  ## useSubmitAction()
436
431
 
437
- `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.
432
+ `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(data)` you can call from any form library.
438
433
 
439
434
  ```tsx
440
435
  import { useSubmitAction } from 'clear-react-router';
@@ -452,8 +447,7 @@ const CreateUserForm = () => {
452
447
  };
453
448
  ```
454
449
 
455
- `submit(formData)` accepts a plain `FormData`, so it works with any form library that gives you
456
- validated values — not just native `<form>` submissions:
450
+ `submit(data: Record<string, unknown>)` accepts a plain JS object, so it works with any form library that gives you validated values — not just native `<form>` submissions:
457
451
 
458
452
  ```tsx
459
453
  import { useForm } from 'react-hook-form';
@@ -461,13 +455,7 @@ import { useForm } from 'react-hook-form';
461
455
  const { register, handleSubmit } = useForm<FormValues>();
462
456
  const { submit, isSubmitting } = useSubmitAction('createUser');
463
457
 
464
- const onValid = (values: FormValues) => {
465
- const formData = new FormData();
466
- Object.entries(values).forEach(([key, value]) => formData.append(key, String(value)));
467
- return submit(formData);
468
- };
469
-
470
- <form onSubmit={handleSubmit(onValid)}>
458
+ <form onSubmit={handleSubmit(submit)}>
471
459
  <input {...register('email')} disabled={isSubmitting} />
472
460
  </form>
473
461
  ```
@@ -480,18 +468,22 @@ Arguments:
480
468
  | `options.onSuccess` | `(data: unknown) => void \| undefined` | `undefined` | Called after a successful submission |
481
469
  | `options.onError` | `(error: unknown) => void \| undefined` | `undefined` | Called if the action throws |
482
470
  | `options.autoReset` | `boolean \| undefined` | `true` | Reset the form element after a successful native submission (`onSubmit` only — has no effect on `submit`) |
483
- | `options.withBeforeLoad` | `boolean \| undefined` | `false` | Whether to run the `beforeLoad` hook on a successful action submit as well |
484
471
 
485
472
  Return value:
486
473
 
487
474
  | Field | Type | Description |
488
475
  |---|---|---|
489
- | `submit` | `(formData: FormData) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
476
+ | `submit` | `(data: Record<string, unknown>) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
490
477
  | `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
491
478
  | `data` | `unknown` | Result of the last successful submission |
492
479
  | `error` | `Error \| null` | Error from the last failed submission |
493
480
  | `isSubmitting` | `boolean` | `true` while the action is in flight |
494
481
 
482
+ > The native `onSubmit` handler converts the form via `Object.fromEntries(new FormData(...))` —
483
+ > if your form has multiple fields sharing the same `name` (checkbox groups, `<select multiple>`),
484
+ > only the last value survives. Use `submit(data)` with your own data source (e.g. React Hook Form)
485
+ > if you need to preserve multiple values per field.
486
+
495
487
  ## useAction()
496
488
 
497
489
  `useAction` provides direct access to a route action.
@@ -504,17 +496,12 @@ Return value:
504
496
  | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
505
497
 
506
498
  ```ts
507
- type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void }> | undefined;
499
+ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void };
508
500
  ```
509
501
 
510
502
  ```tsx
511
503
  const save = useAction('save');
512
-
513
- const handleClick = async () => {
514
- const data = new FormData();
515
- data.append('title', 'Hello');
516
- await save(data);
517
- };
504
+ const handleClick = async () => await save({ data: 'Hello world!' });
518
505
 
519
506
  <button onClick={handleClick}>Save</button>
520
507
  ```
@@ -544,7 +531,7 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
544
531
  Returns a function to navigate programmatically. Accepts a string (pathname, optionally with a `?query`), a `NavigationLocation` object, or `-1` to go back.
545
532
 
546
533
  ```tsx
547
- type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
534
+ type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
548
535
 
549
536
  const navigate = useNavigate();
550
537
 
@@ -553,7 +540,7 @@ navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: '
553
540
  navigate(-1); // go back
554
541
  ```
555
542
 
556
- **Note:** Navigation state can be accessed via `useLocation()`:
543
+ **Note:** Navigation state can be accessed via [`useLocation()`](#uselocation):
557
544
 
558
545
  ```tsx
559
546
  const navigate = useNavigate();
@@ -577,8 +564,39 @@ const params = useParams<{ userId: string }>();
577
564
 
578
565
  Returns current location `{ pathname, search, state }`.
579
566
  ```tsx
567
+ type Location = {
568
+ pathname: string;
569
+ search?: string;
570
+ state?: unknown;
571
+ prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
572
+ }
573
+
580
574
  const { pathname, search, state } = useLocation();
581
575
  ```
576
+ ### Where you came from
577
+
578
+ Every `location` carries `prevLocation` — the pathname and search of the route you
579
+ navigated away from. Useful for a contextual "Back" link, or for redirect logic in
580
+ `beforeLoad`:
581
+
582
+ ```tsx
583
+ const location = useLocation();
584
+
585
+ <Link to={location.prevLocation?.pathname ?? '/'}>← Back</Link>
586
+ ```
587
+
588
+ ```tsx
589
+ // beforeLoad
590
+ beforeLoad: async ({ location, redirect }) => {
591
+ if (!isAuthenticated && location.prevLocation?.pathname !== '/login') {
592
+ await redirect('/login');
593
+ }
594
+ }
595
+ ```
596
+
597
+ > `prevLocation` reflects only the immediately preceding route — it doesn't accumulate
598
+ > a full navigation history, and it's `undefined` on the very first render (nothing to
599
+ > navigate away from yet).
582
600
 
583
601
  ### `useLoaderState<T>()`
584
602
 
@@ -1,4 +1,4 @@
1
- export declare const useAction: (action: string, options?: import("../types").Options) => (arg: FormData) => Promise<{
1
+ export declare const useAction: (action: string, options?: import("../types").Options) => (arg: Record<string, unknown>) => Promise<{
2
2
  data: unknown;
3
3
  error: Error | null;
4
4
  }>;
@@ -3,10 +3,9 @@ type Options = {
3
3
  onSuccess?(arg: unknown): void;
4
4
  onError?(arg: unknown): void;
5
5
  autoReset?: boolean;
6
- withBeforeLoad?: boolean;
7
6
  };
8
7
  export declare const useSubmitAction: (action: string, options?: Options) => {
9
- submit: (formData: FormData) => Promise<{
8
+ submit: (data: Record<string, unknown>) => Promise<{
10
9
  data: unknown;
11
10
  error: Error | null;
12
11
  }>;
package/dist/index.js CHANGED
@@ -47,7 +47,7 @@ var EMPTY_LOADER_STATE = {};
47
47
  var WINDOW_TOP = "__window_top__";
48
48
  var WINDOW_LEFT = "__window_left__";
49
49
  //#endregion
50
- //#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
50
+ //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
51
51
  function _typeof(o) {
52
52
  "@babel/helpers - typeof";
53
53
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -57,7 +57,7 @@ function _typeof(o) {
57
57
  }, _typeof(o);
58
58
  }
59
59
  //#endregion
60
- //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPrimitive.js
60
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
61
61
  function toPrimitive(t, r) {
62
62
  if ("object" != _typeof(t) || !t) return t;
63
63
  var e = t[Symbol.toPrimitive];
@@ -69,13 +69,13 @@ function toPrimitive(t, r) {
69
69
  return ("string" === r ? String : Number)(t);
70
70
  }
71
71
  //#endregion
72
- //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPropertyKey.js
72
+ //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
73
73
  function toPropertyKey(t) {
74
74
  var i = toPrimitive(t, "string");
75
75
  return "symbol" == _typeof(i) ? i : i + "";
76
76
  }
77
77
  //#endregion
78
- //#region \0@oxc-project+runtime@0.133.0/helpers/esm/defineProperty.js
78
+ //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
79
79
  function _defineProperty(e, r, t) {
80
80
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
81
81
  value: t,
@@ -236,10 +236,6 @@ var createNavigate = (routerState, revalidateCache) => {
236
236
  return abortController.signal;
237
237
  };
238
238
  const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
239
- const getContext = () => ({
240
- context: contextState.getState(),
241
- setContext: contextState.setState
242
- });
243
239
  const routeResolve = (location) => {
244
240
  const nextItem = findRoute(location.pathname, true);
245
241
  return {
@@ -250,7 +246,20 @@ var createNavigate = (routerState, revalidateCache) => {
250
246
  const beforeLoad = async (routeItem, nextLocation) => {
251
247
  const { defaultBeforeLoad } = routerConfig;
252
248
  const runBeforeLoad = async (loaderFn) => {
253
- const redirect = async (redirected) => await navigate(typeof redirected === "string" ? { pathname: redirected } : redirected);
249
+ const redirect = async (redirected) => {
250
+ const { location } = routeItemDataState.getState();
251
+ const prevLocation = {
252
+ pathname: location.pathname,
253
+ search: location.search
254
+ };
255
+ return await navigate(typeof redirected === "string" ? {
256
+ pathname: redirected,
257
+ prevLocation
258
+ } : {
259
+ ...redirected,
260
+ prevLocation
261
+ });
262
+ };
254
263
  try {
255
264
  await loaderFn({
256
265
  redirect,
@@ -328,14 +337,14 @@ var createNavigate = (routerState, revalidateCache) => {
328
337
  };
329
338
  const afterLoad = async (routeItem, params) => {
330
339
  const { defaultAfterLoad } = routerConfig;
331
- if (routeItem?.afterLoad) await routeItem.afterLoad({
332
- ...getContext(),
333
- params
334
- });
335
- if (defaultAfterLoad) await defaultAfterLoad({
336
- ...getContext(),
337
- params
338
- });
340
+ const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
341
+ const args = {
342
+ context: contextState.getState(),
343
+ params,
344
+ searchParams
345
+ };
346
+ if (routeItem?.afterLoad) await routeItem.afterLoad(args);
347
+ if (defaultAfterLoad) await defaultAfterLoad(args);
339
348
  };
340
349
  const checkBlocked = (nextLocation) => {
341
350
  if (blockerState.getState() === "charged") {
@@ -385,7 +394,7 @@ var createNavigate = (routerState, revalidateCache) => {
385
394
  loaderStateValue
386
395
  }));
387
396
  clearCurrentGcTimeout(nextItem, nextLocation);
388
- await afterLoad(nextItem, params);
397
+ afterLoad(nextItem, params);
389
398
  };
390
399
  return navigate;
391
400
  };
@@ -610,30 +619,34 @@ var createRouterInstance = () => {
610
619
  const { routeItem, location } = routerState.routeItemDataState.getState();
611
620
  return getParams(location, routeItem);
612
621
  },
613
- useNavigate: () => {
622
+ useNavigate: () => async (arg) => {
614
623
  const { location } = routerState.routeItemDataState.getState();
615
- return async (arg) => {
616
- if (arg === -1) return history.go(arg);
617
- if (typeof arg === "string") {
618
- const [pathname, search = ""] = arg.split("?");
619
- if (pathname !== location.pathname || search !== location.search) await navigate({
620
- pathname,
621
- search
622
- });
623
- return;
624
- }
625
- const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
626
- await navigate({
627
- ...arg,
628
- search
629
- });
624
+ const prevLocation = {
625
+ pathname: location.pathname,
626
+ search: location.search
630
627
  };
628
+ if (arg === -1) return history.go(arg);
629
+ if (typeof arg === "string") {
630
+ const [pathname, search = ""] = arg.split("?");
631
+ if (pathname !== location.pathname || search !== location.search) await navigate({
632
+ pathname,
633
+ search,
634
+ prevLocation
635
+ });
636
+ return;
637
+ }
638
+ const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
639
+ await navigate({
640
+ ...arg,
641
+ search,
642
+ prevLocation
643
+ });
631
644
  },
632
645
  useAction: (action, options = {}) => {
633
646
  const currentAction = getCurrentAction(action);
634
- return async (formData) => {
647
+ return async (input) => {
635
648
  try {
636
- const data = await currentAction(formData);
649
+ const data = await currentAction(input);
637
650
  await invalidate();
638
651
  options.onSuccess?.(data);
639
652
  return {
@@ -669,8 +682,16 @@ var useNavigation = () => {
669
682
  useEffect(() => {
670
683
  const handler = async (event) => {
671
684
  const newLocation = parseWindowLocation(event.target.location);
685
+ const { location } = routeItemDataState.getState();
686
+ const prevLocation = {
687
+ pathname: location.pathname,
688
+ search: location.search
689
+ };
672
690
  if (blockerState.getState() === "charged") history.pushState(null, "", routeItemDataState.getState().location.pathname);
673
- await navigate(newLocation);
691
+ await navigate({
692
+ ...newLocation,
693
+ prevLocation
694
+ });
674
695
  };
675
696
  window.addEventListener("popstate", handler);
676
697
  return () => window.removeEventListener("popstate", handler);
@@ -1084,9 +1105,9 @@ var useSubmitAction = (action, options) => {
1084
1105
  const [data, setData] = useState();
1085
1106
  const [error, setError] = useState(null);
1086
1107
  const [isSubmitting, setIsSubmitting] = useState(false);
1087
- const submit = useCallback(async (formData) => {
1108
+ const submit = useCallback(async (data) => {
1088
1109
  setIsSubmitting(true);
1089
- const result = await currentAction(formData);
1110
+ const result = await currentAction(data);
1090
1111
  setIsSubmitting(false);
1091
1112
  setData(result.data);
1092
1113
  setError(result.error);
@@ -1097,7 +1118,7 @@ var useSubmitAction = (action, options) => {
1097
1118
  onSubmit: useCallback(async (evt) => {
1098
1119
  evt.preventDefault();
1099
1120
  const target = evt.target;
1100
- const { error } = await submit(new FormData(target));
1121
+ const { error } = await submit(Object.fromEntries(new FormData(target)));
1101
1122
  if (!(options?.autoReset === false) && !error) target.reset();
1102
1123
  }, [options?.autoReset, submit]),
1103
1124
  data,
@@ -1,2 +1,2 @@
1
- import { RevalidateCache, RouterState } from '../types';
1
+ import { RevalidateCache, RouterState, Location } from '../types';
2
2
  export declare const createPrefetch: ({ routeItemDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
package/dist/types.d.ts CHANGED
@@ -41,9 +41,9 @@ export type ClientRouteItem = {
41
41
  afterLoad?: (arg: {
42
42
  context: Record<string, unknown>;
43
43
  params: Record<string, string>;
44
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
45
- }) => Promise<void>;
46
- actions?: (arg: LoaderArgs) => Record<string, (arg: FormData) => Promise<unknown> | Promise<void> | void | unknown>;
44
+ searchParams: Record<string, string>;
45
+ }) => Promise<void> | void;
46
+ actions?: (arg: LoaderArgs) => Record<string, (arg: Record<string, unknown>) => Promise<unknown> | Promise<void> | void | unknown>;
47
47
  };
48
48
  export type RouteItem = ClientRouteItem & {
49
49
  element: RenderElement;
@@ -57,6 +57,7 @@ export type Location = {
57
57
  pathname: string;
58
58
  search?: string;
59
59
  state?: unknown;
60
+ prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
60
61
  };
61
62
  export type BlockerState = 'blocked' | 'unblocked' | 'charged';
62
63
  export type RevalidateCacheArgs = {
@@ -141,7 +142,7 @@ export type RouterType = {
141
142
  useLoaderState<T>(): LoaderState<T>;
142
143
  useParams<T>(): T;
143
144
  useNavigate(): (arg: NavigationLocation | string | -1) => Promise<void>;
144
- useAction(action: string, options?: Options): (arg: FormData) => Promise<{
145
+ useAction(action: string, options?: Options): (arg: Record<string, unknown>) => Promise<{
145
146
  data: unknown;
146
147
  error: Error | null;
147
148
  }>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.1",
3
+ "version": "2.2.3",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {