Skip to content

Commit

Permalink
app: Don't use useRandomHistory if not needed
Browse files Browse the repository at this point in the history
  • Loading branch information
evanpurkhiser committed Jan 13, 2021
1 parent 4f82a28 commit 98c0fa6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
11 changes: 8 additions & 3 deletions src/overlay/overlays/nowPlaying/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,17 @@ type ExampleProps = {
};

const Example: React.FC<ExampleProps> = observer(({store, config, hideControls}) => {
const demoHistory = useRandomHistory({cutoff: 5, updateInterval: 5000});
const liveHistory = store.mixstatus.trackHistory;

const history = liveHistory.length === 0 ? demoHistory : liveHistory;
const isLive = liveHistory.length > 0;

const demoHistory = useRandomHistory({
enabled: !isLive,
cutoff: 5,
updateInterval: 5000,
});

const history = isLive ? liveHistory : demoHistory;

const theme = config?.theme ?? 'tracklist';
const Overlay = themes[theme].component;

Expand Down
12 changes: 8 additions & 4 deletions src/utils/useRandomHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import {PlayedTrack} from 'src/shared/store';
import {makeRandomTrack} from './randomMetadata';

type Options = {
/**
* Should we continue to produce random history data
*/
enabled: boolean;
/**
* Maximum number of history items to store
*/
Expand All @@ -19,17 +23,17 @@ type Options = {
* Generates a random track history from a random music metadata API + random
* image API.
*/
const useRandomHistory = ({cutoff, updateInterval}: Options) => {
const useRandomHistory = ({enabled, cutoff, updateInterval}: Options) => {
const [history, setHistory] = React.useState<PlayedTrack[]>([]);

let isUpdating = true;

const startUpdater = async () => {
let lastHistory = history;

while (isUpdating) {
while (enabled && isUpdating) {
lastHistory = [...lastHistory, await makeRandomTrack()].slice(-1 * cutoff);
if (isUpdating) {
if (enabled && isUpdating) {
setHistory(lastHistory);
await new Promise(r => setTimeout(r, updateInterval));
}
Expand All @@ -41,7 +45,7 @@ const useRandomHistory = ({cutoff, updateInterval}: Options) => {
return () => {
isUpdating = false;
};
}, [cutoff, updateInterval]);
}, [enabled, cutoff, updateInterval]);

return history;
};
Expand Down

0 comments on commit 98c0fa6

Please sign in to comment.