2020-12-03 18:29:47 +01:00
|
|
|
// @flow
|
|
|
|
import React from 'react';
|
|
|
|
import { lighthouse } from 'redux/actions/search';
|
|
|
|
import { getSearchQueryString } from 'util/query-params';
|
2021-01-28 20:03:37 +01:00
|
|
|
import { isURIValid } from 'lbry-redux';
|
2020-12-03 18:29:47 +01:00
|
|
|
import useThrottle from './use-throttle';
|
|
|
|
|
2021-06-03 04:59:01 +02:00
|
|
|
export default function useLighthouse(
|
|
|
|
query: string,
|
2021-06-23 05:40:13 +02:00
|
|
|
showMature: boolean,
|
|
|
|
size: number = 5,
|
|
|
|
additionalOptions: any = {},
|
|
|
|
throttleMs: number = 500
|
2021-06-03 04:59:01 +02:00
|
|
|
) {
|
2020-12-03 18:29:47 +01:00
|
|
|
const [results, setResults] = React.useState();
|
|
|
|
const [loading, setLoading] = React.useState();
|
2021-06-03 04:59:01 +02:00
|
|
|
const queryString = query ? getSearchQueryString(query, { nsfw: showMature, size, ...additionalOptions }) : '';
|
2021-06-23 05:40:13 +02:00
|
|
|
const throttledQuery = useThrottle(queryString, throttleMs);
|
2020-12-03 18:29:47 +01:00
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
if (throttledQuery) {
|
|
|
|
setLoading(true);
|
|
|
|
setResults(null);
|
|
|
|
|
2020-12-11 19:42:54 +01:00
|
|
|
let isSubscribed = true;
|
2020-12-03 18:29:47 +01:00
|
|
|
lighthouse
|
|
|
|
.search(throttledQuery)
|
2021-08-17 16:03:25 +02:00
|
|
|
.then(({ body: results }) => {
|
2020-12-11 19:42:54 +01:00
|
|
|
if (isSubscribed) {
|
2021-06-03 04:59:01 +02:00
|
|
|
setResults(
|
|
|
|
results.map((result) => `lbry://${result.name}#${result.claimId}`).filter((uri) => isURIValid(uri))
|
|
|
|
);
|
2020-12-11 19:42:54 +01:00
|
|
|
setLoading(false);
|
|
|
|
}
|
2020-12-03 18:29:47 +01:00
|
|
|
})
|
|
|
|
.catch(() => {
|
|
|
|
setLoading(false);
|
|
|
|
});
|
2020-12-11 19:42:54 +01:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
isSubscribed = false;
|
|
|
|
};
|
2020-12-03 18:29:47 +01:00
|
|
|
}
|
|
|
|
}, [throttledQuery]);
|
|
|
|
|
|
|
|
return { results, loading };
|
|
|
|
}
|