Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: export useMatchedRoute hook for theme #2165

Merged
merged 4 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
};
Loading