Pull out livestream data-fetch into an effect.
Differences with the original from 'livestreamList/view.jsx': - Returns null instead of an empty object for the empty case. This removes the need for clients to create a temp array to determine if the list is empty ('Object.keys(x).length'). - Allow option to not periodically refresh by setting the interval to 0.
This commit is contained in:
parent
44195ec239
commit
355bc9296c
1 changed files with 52 additions and 0 deletions
52
ui/effects/use-get-livestreams.js
Normal file
52
ui/effects/use-get-livestreams.js
Normal file
|
@ -0,0 +1,52 @@
|
|||
// @flow
|
||||
import React from 'react';
|
||||
import { BITWAVE_LIVE_API } from 'constants/livestream';
|
||||
|
||||
/**
|
||||
* Gets latest livestream info list. Returns null (instead of a blank object)
|
||||
* when there are no active livestreams.
|
||||
*
|
||||
* @param refreshMs
|
||||
* @returns {{livestreamMap: null, loading: boolean}}
|
||||
*/
|
||||
export default function useGetLivestreams(refreshMs: number) {
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [livestreamMap, setLivestreamMap] = React.useState(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
function checkCurrentLivestreams() {
|
||||
fetch(BITWAVE_LIVE_API)
|
||||
.then((res) => res.json())
|
||||
.then((res) => {
|
||||
setLoading(false);
|
||||
if (!res.data) {
|
||||
setLivestreamMap(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const livestreamMap = res.data.reduce((acc, curr) => {
|
||||
acc[curr.claimId] = curr;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
setLivestreamMap(livestreamMap);
|
||||
})
|
||||
.catch((err) => {
|
||||
setLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
checkCurrentLivestreams();
|
||||
|
||||
if (refreshMs > 0) {
|
||||
let fetchInterval = setInterval(checkCurrentLivestreams, refreshMs);
|
||||
return () => {
|
||||
if (fetchInterval) {
|
||||
clearInterval(fetchInterval);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { livestreamMap, loading };
|
||||
}
|
Loading…
Reference in a new issue