|
6 | 6 | * LICENSE file in the root directory of this source tree. |
7 | 7 | */ |
8 | 8 |
|
9 | | -import { useEffect, useMemo, useState } from 'react'; |
| 9 | +import { createContext, useContext, useEffect, useMemo, useState } from 'react'; |
10 | 10 | import { useAdapter } from '@object-ui/app-shell'; |
11 | 11 | import { buildPortalBooks, type Book, type ResolverDoc } from './book-nav'; |
12 | 12 |
|
@@ -77,7 +77,12 @@ interface RawState { |
77 | 77 | error?: string; |
78 | 78 | } |
79 | 79 |
|
80 | | -export function useBookData(): BookData { |
| 80 | +/** |
| 81 | + * Fetch the book + doc metadata once. Used by {@link BookDataProvider} at the |
| 82 | + * `/docs` layout route so the whole docs section shares a single fetch, rather |
| 83 | + * than each page (index, book landing, reader) re-fetching independently. |
| 84 | + */ |
| 85 | +function useBookDataFetch(): BookData { |
81 | 86 | const adapter = useAdapter(); |
82 | 87 | const [data, setData] = useState<RawState>({ authoredBooks: [], docs: [], state: 'loading' }); |
83 | 88 |
|
@@ -125,3 +130,20 @@ export function useBookData(): BookData { |
125 | 130 |
|
126 | 131 | return { ...data, books }; |
127 | 132 | } |
| 133 | + |
| 134 | +const LOADING: BookData = { authoredBooks: [], books: [], docs: [], state: 'loading' }; |
| 135 | + |
| 136 | +/** |
| 137 | + * Shared book/doc data, provided once at the `/docs` layout route (see |
| 138 | + * DocsLayout) and consumed by {@link useBookData}. Exported so the layout's |
| 139 | + * provider — which lives in a `.tsx` file — can supply it. |
| 140 | + */ |
| 141 | +export const BookDataContext = createContext<BookData | null>(null); |
| 142 | + |
| 143 | +/** The one-time fetcher the layout drives. Internal to the docs section. */ |
| 144 | +export { useBookDataFetch }; |
| 145 | + |
| 146 | +/** Read the shared book/doc data. Returns a loading state outside the provider. */ |
| 147 | +export function useBookData(): BookData { |
| 148 | + return useContext(BookDataContext) ?? LOADING; |
| 149 | +} |
0 commit comments