-
Notifications
You must be signed in to change notification settings - Fork 371
/
Copy pathuseSearch.tsx
55 lines (47 loc) · 1.48 KB
/
useSearch.tsx
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
import { SearchContextState } from "@elastic/search-ui";
import { useContext, useEffect, useState } from "react";
import SearchContext from "../SearchContext";
/**
* React hook that provides access to Search UI state and actions
*
* @param mapContextToProps Optional function to select specific parts of the context
* @returns Selected search context state and actions
*/
export function useSearch<T = SearchContextState>(
mapContextToProps?: (context: SearchContextState) => T
): T {
const context = useContext(SearchContext);
if (!context) {
throw new Error("useSearch must be used within a SearchProvider");
}
const [state, setState] = useState<T>(() =>
mapContextToProps
? mapContextToProps({
...context.driver.getState(),
...context.driver.getActions()
})
: ({
...context.driver.getState(),
...context.driver.getActions()
} as T)
);
useEffect(() => {
const subscription = (newState: Partial<SearchContextState>) => {
setState((prevState: T) => {
const fullContext = {
...(prevState as any),
...newState
};
return mapContextToProps
? mapContextToProps(fullContext)
: (fullContext as T);
});
};
context.driver.subscribeToStateChanges(subscription);
return () => {
context.driver.unsubscribeToStateChanges(subscription);
};
}, [context.driver, mapContextToProps]);
return state;
}
export default useSearch;