lbry-desktop/ui/effects/use-lighthouse.js

40 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

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';
export default function useLighthouse(query: string, showMature?: boolean, size?: number = 5) {
const [results, setResults] = React.useState();
const [loading, setLoading] = React.useState();
2020-12-11 19:33:27 +01:00
const queryString = query ? getSearchQueryString(query, { nsfw: showMature, size }) : '';
2020-12-03 18:29:47 +01:00
const throttledQuery = useThrottle(queryString, 500);
React.useEffect(() => {
if (throttledQuery) {
setLoading(true);
setResults(null);
let isSubscribed = true;
2020-12-03 18:29:47 +01:00
lighthouse
.search(throttledQuery)
.then(results => {
if (isSubscribed) {
2021-01-28 20:03:37 +01:00
setResults(results.map(result => `lbry://${result.name}#${result.claimId}`).filter(uri => isURIValid(uri)));
setLoading(false);
}
2020-12-03 18:29:47 +01:00
})
.catch(() => {
setLoading(false);
});
return () => {
isSubscribed = false;
};
2020-12-03 18:29:47 +01:00
}
}, [throttledQuery]);
return { results, loading };
}