Skip to content

Commit

Permalink
feat: export useMatchedRoute hook for theme (#2165)
Browse files Browse the repository at this point in the history
* feat: export `useMatchRoute` feature hooks

* docs: update

* chore: rename

* docs: update
  • Loading branch information
Wxh16144 authored Jul 26, 2024
1 parent 7aa2503 commit 0d1dc35
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
22 changes: 22 additions & 0 deletions docs/theme/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,28 @@ const Example = () => {
};
```

### useMatchedRoute

- 作用:获取当前匹配的路由数据
- 场景:搭配 getRouteMetaById API 可自定义获取页面元数据
- 用法:

```ts
import { useMatchedRoute, getRouteMetaById, type IRouteMeta } from 'dumi';
import useSWR from 'swr';

export function useMeta() {
const route = useMatchedRoute();

useSWR(route.id, getRouteMetaById, {
onSuccess: (meta: IRouteMeta) => {
// do something with meta
globalThis.console.log(meta);
},
});
}
```

### useRouteMeta

- 作用:获取当前路由的元数据
Expand Down
2 changes: 1 addition & 1 deletion src/client/theme-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export { useLiveDemo } from './useLiveDemo';
export { useLocale } from './useLocale';
export { useNavData } from './useNavData';
export { usePrefersColor } from './usePrefersColor';
export { useRouteMeta } from './useRouteMeta';
export { useMatchedRoute, useRouteMeta } from './useRouteMeta';
export { useFullSidebarData, useSidebarData } from './useSidebarData';
export { useSiteSearch } from './useSiteSearch';
export { useTabMeta } from './useTabMeta';
18 changes: 14 additions & 4 deletions src/client/theme-api/useRouteMeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ function getCachedRouteMeta(route: IRoutesById[string]) {
}

/**
* hook for get matched route meta
* hook for get matched route
* @internal internal use. Do not use in your production code.
*/
export const useRouteMeta = () => {
export const useMatchedRoute = () => {
const { route } = useRouteData();
const { pathname } = useLocation();
const { clientRoutes } = useAppData();
Expand All @@ -95,12 +96,21 @@ export const useRouteMeta = () => {

return ret;
}, [clientRoutes.length, pathname]);

const [matchedRoute, setMatchedRoute] = useState(getter);
const meta = getCachedRouteMeta(matchedRoute);

useIsomorphicLayoutEffect(() => {
setMatchedRoute(getter);
}, [clientRoutes.length, pathname]);

return meta;
return matchedRoute;
};

/**
* hook for get matched route meta
*/
export const useRouteMeta = () => {
const route = useMatchedRoute();

return getCachedRouteMeta(route);
};

0 comments on commit 0d1dc35

Please sign in to comment.