-
Notifications
You must be signed in to change notification settings - Fork 0
/
useFindEntry.ts
34 lines (29 loc) · 1.11 KB
/
useFindEntry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import type { Entry } from '../../contentful/types'
import { hasResolveEntry } from '../../resolve'
import { useQuery, UseQueryOptions, UseQueryResult } from './useQuery'
export type UseFindEntryResult<T> =
UseQueryResult<Entry<T> | null | undefined>
/**
* Queries the dataSource for an entry by ID.
* The entry will be resolved down to the specified depth if provided.
*
* If the entry does not exist, the result will be null.
* The result will be undefined while the query is loading.
*/
export function useFindEntry<T extends Record<string, unknown> = any>(
id: string,
options?: UseQueryOptions & { include?: number },
/** Overrides the dependency list to control when the query is re-run */
deps?: React.DependencyList
): UseFindEntryResult<T> {
return useQuery<Entry<T> | null | undefined>(
async (dataSource) => {
let result = await dataSource.getEntry<T>(id)
if (result && options?.include && hasResolveEntry(dataSource)) {
result = await dataSource.resolveEntry<T>(result, options.include)
}
return result || null
},
options,
deps || [id, options?.include])
}