Skip to content

Commit

Permalink
fix(hooks): useProgress & usePlayback hooks (#1723)
Browse files Browse the repository at this point in the history
* fix(js): fix useProgress & usePlayback hooks

- (breaking) fix: usePlaybackState was incorrectly returning State.None by default. Now it returns undefined while it is waiting on the async call to TrackPlayer to resolve. This also fixes the following issue where duration was incorrectly being reported as `0`: #1709
- optimization: avoid unnecessarily reevaluating the useEffect on every player state change by moving the `playerState === State.None` outside of the effect and including it as a dependency instead

* chore(js): make hooks fix non-breaking
  • Loading branch information
puckey authored Sep 14, 2022
1 parent 57de8b5 commit 31fa40a
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { useEffect, useRef, useState } from 'react';
import { Event, EventsPayloadByEvent, Progress, State } from './interfaces';
import TrackPlayer from './trackPlayer';

/** Get current playback state and subsequent updates */
export const usePlaybackState = () => {
const [state, setState] = useState(State.None);
const usePlaybackStateWithoutInitialValue = () => {
const [state, setState] = useState<State | undefined>(undefined);
useEffect(() => {
let mounted = true;

Expand Down Expand Up @@ -35,6 +34,12 @@ export const usePlaybackState = () => {
return state;
};

/** Get current playback state and subsequent updates */
export const usePlaybackState = () => {
const state = usePlaybackStateWithoutInitialValue();
return state ?? State.None;
};

/**
* Attaches a handler to the given TrackPlayer events and performs cleanup on unmount
* @param events - TrackPlayer events to subscribe to
Expand Down Expand Up @@ -88,11 +93,11 @@ export function useProgress(updateInterval = 1000) {
duration: 0,
buffered: 0,
});
const playerState = usePlaybackState();

const playerState = usePlaybackStateWithoutInitialValue();
const isNone = playerState === State.None;
useEffect(() => {
let mounted = true;
if (playerState === State.None) {
if (isNone) {
setState({ position: 0, duration: 0, buffered: 0 });
return;
}
Expand Down Expand Up @@ -131,7 +136,7 @@ export function useProgress(updateInterval = 1000) {
return () => {
mounted = false;
};
}, [playerState, updateInterval]);
}, [isNone, updateInterval]);

return state;
}

0 comments on commit 31fa40a

Please sign in to comment.