-
Notifications
You must be signed in to change notification settings - Fork 0
/
useSubjectList.jsx
57 lines (44 loc) · 1.46 KB
/
useSubjectList.jsx
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { useEffect, useState } from 'react';
import { getConfig } from '@edx/frontend-platform';
import algoliasearch from 'algoliasearch';
import algoliasearchHelper from 'algoliasearch-helper';
import { defaultSubjectList } from '../constants';
const PRODUCT_INDEX = 'product';
const SUBJECT_FACET = 'subject';
const getAlgoliaSearchClient = () => algoliasearch(
getConfig().AUTHN_ALGOLIA_APP_ID,
getConfig().AUTHN_ALGOLIA_SEARCH_API_KEY,
);
const parseSubjectsFromAlgoliaResults = (subjectsList) => (
subjectsList.map(subject => ({ label: subject.name }))
);
const useSubjectsList = () => {
const [subjectsList, setSubjectsList] = useState([]);
const [subjectsLoading, setSubjectsLoading] = useState(true);
useEffect(() => {
const searchClient = getAlgoliaSearchClient();
const searchHelper = algoliasearchHelper(
searchClient,
PRODUCT_INDEX,
{ facets: [SUBJECT_FACET] },
);
const searchIndex = () => {
setSubjectsLoading(true);
searchHelper.search();
};
searchIndex();
searchHelper.on('result', ({ results }) => {
setSubjectsList(parseSubjectsFromAlgoliaResults(results.getFacetValues(SUBJECT_FACET, {})));
setSubjectsLoading(false);
});
searchHelper.on('error', () => {
setSubjectsLoading(false);
setSubjectsList(parseSubjectsFromAlgoliaResults(defaultSubjectList));
});
}, []);
return {
subjectsList,
subjectsLoading,
};
};
export default useSubjectsList;