Skip to content

Commit 5538d9d

Browse files
committed
refactor: fetch orama-db when search triggered
1 parent 2765300 commit 5538d9d

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

src/generators/web/ui/hooks/useOrama.mjs

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,48 @@
11
import { create, search, load } from '@orama/orama';
2-
import { useState, useEffect } from 'react';
2+
import { useState, useEffect, useRef } from 'react';
33

44
import { relativeOrAbsolute } from '../utils/relativeOrAbsolute.mjs';
55

66
/**
7-
* Hook for initializing and managing Orama search database
7+
* Hook for initializing and managing Orama search database.
8+
* The search data is lazily fetched on the first search call.
89
*
910
* @param {string} pathname - The current page's path (e.g., '/api/fs')
1011
*/
1112
export default pathname => {
1213
const [client, setClient] = useState(null);
14+
const loaded = useRef(null);
1315

1416
useEffect(() => {
1517
// Create the database instance
1618
const db = create({
1719
schema: {},
1820
});
1921

22+
/**
23+
* Ensures the search data is loaded.
24+
* @returns {Promise<void>} A promise that resolves when the data is loaded.
25+
*/
26+
const ensureLoaded = () => {
27+
if (!loaded.current) {
28+
loaded.current = fetch(relativeOrAbsolute('/orama-db.json', pathname))
29+
.then(response => response.ok && response.json())
30+
.then(data => load(db, data));
31+
}
32+
33+
return loaded.current;
34+
};
35+
2036
// TODO(@avivkeller): Ask Orama to support this functionality natively
2137
/**
2238
* @param {any} options
2339
*/
24-
db.search = options => search(db, options);
40+
db.search = async options => {
41+
await ensureLoaded();
42+
return search(db, options);
43+
};
2544

2645
setClient(db);
27-
28-
// Load the search data
29-
fetch(relativeOrAbsolute('/orama-db.json', pathname))
30-
.then(response => response.ok && response.json())
31-
.then(data => load(db, data));
3246
}, []);
3347

3448
return client;

0 commit comments

Comments
 (0)