Skip to content

Commit 3d00fa8

Browse files
authored
refactor: fetch orama-db.json when search triggered (#759)
* refactor: fetch orama-db when search triggered * fix: null ref when fetch catch
1 parent e96a883 commit 3d00fa8

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

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

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,51 @@
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+
.catch(() => {
32+
loaded.current = null;
33+
});
34+
}
35+
36+
return loaded.current;
37+
};
38+
2039
// TODO(@avivkeller): Ask Orama to support this functionality natively
2140
/**
2241
* @param {any} options
2342
*/
24-
db.search = options => search(db, options);
43+
db.search = async options => {
44+
await ensureLoaded();
45+
return search(db, options);
46+
};
2547

2648
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));
3249
}, []);
3350

3451
return client;

0 commit comments

Comments
 (0)