clear-react-router 2.2.8 → 2.3.0

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
@@ -706,20 +706,25 @@ await invalidate('/post/[id]/comment/[id]');
706
706
  ```
707
707
 
708
708
  #### Force revalidation
709
- By default only paths that already exist in the cache are revalidated.
710
- Pass `{ force: true }` to also revalidate the exact path(s) you passed, even if they were never cached:
709
+ By default the exact path(s) you pass are always revalidated, even if they were never cached
710
+ — this also makes `invalidate()` work on an error page with an empty cache.
711
+ Pass `{ force: false }` to go back to cache-only revalidation:
711
712
 
712
713
  ```tsx
713
- await invalidate('/about', { force: true });
714
- await invalidate(['/about', '/post/10'], { force: true });
714
+ await invalidate('/about', { force: false });
715
715
  ```
716
716
 
717
+ Explicit `{ force: true }` behaves the same as the default; it exists for readability
718
+ and for combining with other options (see below).
719
+
717
720
  #### Stale-only revalidation
718
721
  By default, `invalidate` deletes matching cache entries and refetches them.
719
722
  Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
720
723
  ```tsx
721
724
  await invalidate('/notes', { staleOnly: true });
722
725
  ```
726
+ Note: `staleOnly` disables the default force — uncached paths are left alone, so no new
727
+ network requests are started for routes you never visited.
723
728
 
724
729
  #### Including child routes
725
730
 
@@ -754,6 +759,20 @@ will revalidate the cached child routes:
754
759
  /post/23
755
760
  /post/42/comments
756
761
  ```
762
+ #### Status transitions
763
+
764
+ When the revalidated path is the currently active route, a successful revalidation also
765
+ resets its status to `active`, while a failed one sets it to `error` — so recovering from
766
+ an error page is just `await invalidate()`:
767
+
768
+ ```tsx
769
+ // On an errorElement: refetch, and show the page again on success
770
+ await invalidate();
771
+ ```
772
+
773
+ Revalidating any other route never touches the current page status — background refreshes
774
+ stay invisible.
775
+
757
776
  #### Returns
758
777
 
759
778
  An array of objects with the following structure:
@@ -764,8 +783,8 @@ Each object represents a revalidated route, where `path` is the route pathname,
764
783
 
765
784
  #### Notes
766
785
 
767
- * Without `force` option, **only routes that already have cached data** are revalidated.
768
- * With `force: true`, the exact pathnames you pass are always revalidated (and stored in the cache).
786
+ * Without `force: false`, the exact pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
787
+ * With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
769
788
  * Cached data is cleared before the new loader starts.
770
789
  * When used as an event handler, wrap the call in an arrow function:
771
790
 
package/dist/index.js CHANGED
@@ -28,12 +28,15 @@ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
28
28
  };
29
29
  //#endregion
30
30
  //#region utils/commitState.ts
31
- var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
31
+ var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ loaderStateValue, location }) => {
32
32
  const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
33
- routeItemDataState.setState({
34
- routeItem,
35
- location,
36
- status: isError ? "error" : "active"
33
+ routeItemDataState.setState((prevState) => {
34
+ if (prevState.status === "active") return prevState;
35
+ return {
36
+ ...prevState,
37
+ location,
38
+ status: isError ? "error" : "active"
39
+ };
37
40
  });
38
41
  loaderState.setState(loaderStateValue);
39
42
  if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
@@ -277,7 +280,14 @@ var createNavigate = (routerState, revalidateCache) => {
277
280
  const prepareNavigation = (routeItem, location, hasError) => {
278
281
  updateScrollMap(routeItemDataState, scrollMapState);
279
282
  createGcTimeout();
280
- if (hasError) return;
283
+ if (hasError) {
284
+ commitNavigation(() => routeItemDataState.setState({
285
+ routeItem,
286
+ location,
287
+ status: "error"
288
+ }));
289
+ return;
290
+ }
281
291
  const path = getPath(location);
282
292
  if (routeItem?.optimistic && loaderMap.has(path)) {
283
293
  commitNavigation(() => routeItemDataState.setState({
@@ -289,10 +299,18 @@ var createNavigate = (routerState, revalidateCache) => {
289
299
  if (currentLoaderState) loaderState.setState(currentLoaderState);
290
300
  return;
291
301
  }
292
- if (routeItem?.loader && !isCacheItemFresh(path)) commitNavigation(() => routeItemDataState.setState({
302
+ if (routeItem?.loader && !isCacheItemFresh(path)) {
303
+ commitNavigation(() => routeItemDataState.setState({
304
+ routeItem,
305
+ location,
306
+ status: "pending"
307
+ }));
308
+ return;
309
+ }
310
+ commitNavigation(() => routeItemDataState.setState({
293
311
  routeItem,
294
312
  location,
295
- status: "pending"
313
+ status: "active"
296
314
  }));
297
315
  };
298
316
  const polling = (routeItem, nextLocation) => {
@@ -378,7 +396,6 @@ var createNavigate = (routerState, revalidateCache) => {
378
396
  };
379
397
  commitNavigation(() => commitState({
380
398
  location: nextLocation,
381
- routeItem: nextItem,
382
399
  loaderStateValue
383
400
  }));
384
401
  clearCurrentGcTimeout(nextItem, nextLocation);
@@ -401,11 +418,17 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
401
418
  search
402
419
  }
403
420
  });
404
- if (result && path === routePathname) loaderState.setState({
405
- data: result.data,
406
- loaderError: result.error,
407
- beforeLoadError: null
408
- });
421
+ if (result && path === routePathname) {
422
+ loaderState.setState({
423
+ data: result.data,
424
+ loaderError: result.error,
425
+ beforeLoadError: null
426
+ });
427
+ routeItemDataState.setState((prevState) => ({
428
+ ...prevState,
429
+ status: result.error ? "error" : "active"
430
+ }));
431
+ }
409
432
  return {
410
433
  path: pathname,
411
434
  ...result
@@ -416,7 +439,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
416
439
  if (!routeItem) return [];
417
440
  const pathnameSet = /* @__PURE__ */ new Set();
418
441
  for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
419
- if (options?.force) pathnameSet.add(pathname);
442
+ if (options?.force === true || options?.force === void 0 && !options?.staleOnly) pathnameSet.add(pathname);
420
443
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
421
444
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
422
445
  const [parentPath] = pathname.split("?");
@@ -688,6 +711,10 @@ var createRouterInstance = (synchronizer) => {
688
711
  });
689
712
  });
690
713
  });
714
+ },
715
+ useRouteItemDataSelector: (callback) => {
716
+ const state = routerState.routeItemDataState;
717
+ return synchronizer(state.subscribe, () => callback(state.getState()));
691
718
  }
692
719
  }
693
720
  };
@@ -867,26 +894,21 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
867
894
  //#endregion
868
895
  //#region hooks/useIsRoutePending.ts
869
896
  var useIsRoutePending = (routePath) => {
870
- const { useRouteItemData } = router.hooks;
871
- const [routeItemData] = useRouteItemData();
872
- return routeItemData.status === "pending" && routeItemData?.location.pathname === routePath;
897
+ const { useRouteItemDataSelector } = router.hooks;
898
+ return useRouteItemDataSelector(({ location: { pathname }, status }) => pathname === routePath && status === "pending");
873
899
  };
874
900
  //#endregion
875
901
  //#region hooks/useNavigate.ts
876
902
  var useNavigate = router.hooks.useNavigate;
877
903
  //#endregion
878
- //#region hooks/useLocation.ts
879
- var useLocation = () => {
880
- const [routeItemData] = router.hooks.useRouteItemData();
881
- return routeItemData.location;
882
- };
883
- //#endregion
884
904
  //#region components/Link.tsx
885
905
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
906
+ var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
886
907
  var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
908
+ const { useRouteItemDataSelector } = router.hooks;
887
909
  const isPending = useIsRoutePending(to);
888
- const { pathname } = useLocation();
889
910
  const navigate = useNavigate();
911
+ const isActive = useRouteItemDataSelector(({ location: { pathname } }) => comparator(to, pathname, exact));
890
912
  const timeout = useRef(0);
891
913
  const elementRef = useRef(null);
892
914
  const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
@@ -939,7 +961,6 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
939
961
  useEffect(() => () => {
940
962
  if (timeout.current) clearTimeout(timeout.current);
941
963
  }, []);
942
- const isActive = to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
943
964
  const normalizedClassName = typeof className === "function" ? className({
944
965
  isActive,
945
966
  isPending
@@ -960,10 +981,10 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
960
981
  await navigate(location);
961
982
  };
962
983
  return as({
963
- ref: elementRef,
964
- style: normalizedStyle,
965
- className: resultClassName,
966
- onClick: clickHandler,
984
+ "ref": elementRef,
985
+ "style": normalizedStyle,
986
+ "className": resultClassName,
987
+ "onClick": clickHandler,
967
988
  href: `${to}${searchString}`,
968
989
  onMouseEnter,
969
990
  onMouseLeave,
@@ -980,6 +1001,9 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
980
1001
  //#region hooks/useParams.ts
981
1002
  var useParams = router.hooks.useParams;
982
1003
  //#endregion
1004
+ //#region hooks/useLocation.ts
1005
+ var useLocation = () => router.hooks.useRouteItemDataSelector((state) => state.location);
1006
+ //#endregion
983
1007
  //#region hooks/useLoaderState.ts
984
1008
  var useLoaderState = router.hooks.useLoaderState;
985
1009
  //#endregion
@@ -1025,9 +1049,8 @@ var useAction = router.hooks.useAction;
1025
1049
  //#endregion
1026
1050
  //#region hooks/useIsDataLoading.ts
1027
1051
  var useIsDataLoading = () => {
1028
- const { useRouteItemData } = router.hooks;
1029
- const [routeData] = useRouteItemData();
1030
- return routeData.status === "pending";
1052
+ const { useRouteItemDataSelector } = router.hooks;
1053
+ return useRouteItemDataSelector(({ status }) => status) === "pending";
1031
1054
  };
1032
1055
  //#endregion
1033
1056
  //#region hooks/useRouterContext.ts
package/dist/types.d.ts CHANGED
@@ -145,6 +145,7 @@ export type RouterType = {
145
145
  error: Error | null;
146
146
  }>;
147
147
  useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
148
+ useRouteItemDataSelector<T>(callback: (arg: RouteItemData) => T): T;
148
149
  };
149
150
  };
150
151
  export type InvalidateOptions = {
@@ -1,8 +1,7 @@
1
- import { LoaderState, Location, RouteItem, RouterState } from '../types';
1
+ import { LoaderState, Location, RouterState } from '../types';
2
2
  type CommitState = {
3
3
  location: Location;
4
4
  loaderStateValue: LoaderState;
5
- routeItem?: RouteItem;
6
5
  };
7
- export declare const createCommitState: ({ loaderState, routeItemDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
6
+ export declare const createCommitState: ({ loaderState, routeItemDataState, blockerState }: RouterState) => ({ loaderStateValue, location }: CommitState) => void;
8
7
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.8",
3
+ "version": "2.3.0",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {