naumch1k / one-fall

Landing page for ONE FALL, Salem-based melodic punk and hardcore quartet has rapidly made a mark in New England
https://develop--one-fall.netlify.app/
0 stars 0 forks source link

BUG: Ensure Unique Track References in useInitAudioTrackRefs Hook #1

Open naumch1k opened 1 month ago

naumch1k commented 1 month ago

Is your feature request related to a problem? Please describe.

In our project, we currently use a custom useInitAudioTrackRefs hook to create a reference for each track's audio element on our page. These refs are later used to obtain the duration of each track, calculate album duration, start and pause track playback, and get the timestamp, audio object currentTime property, of the playing track to display the player's progress.

useInitAudioTrackRefs iterates through all the albums and collects tracks into a single array.

const [tracks, setTracks] = useState<ITrack[]>([])

  useEffect(() => {
    const getAllTracks = (data: { items: IAlbum[] }) => {
      let allTracks: ITrack[] = []

      data.items.forEach(album => {
        album.tracks.items.forEach((track: ITrack) => allTracks.push(track))
      })

      setTracks(allTracks)
    }

    getAllTracks(data)
  }, [data])

Then, a key-value pair is created in the audioTrackRefs object for each track in the tracks array. The key is set to the track's name.

  const audioTrackRefs: Record<string, TAudioRef> = {}

  tracks.forEach(track => audioTrackRefs[track.name] = createRef<HTMLAudioElement>())

The potential problem here is that if two albums have tracks with the same name (which is not uncommon in the music industry, e.g., Greatest Hits), the reference created for the second track will overwrite the reference created for the first track. This can lead to incorrect duration calculations for tracks and albums and playing the wrong track.

Describe the solution you'd like

To avoid key collisions, we should use a unique identifier for each track as the key. This could be a combination of the album name and the track name, or a unique track ID if available.

const uniqueKey = `${track.albumName}-${track.name}`

The proposed solution requires updating useAlbumInfo and useAudioTrackDuration hooks to use these unique keys.

Describe alternatives you've considered

When we integrate with a database or a CMS, we could leverage the unique identifier (e.g., _id or equivalent) provided by the database or CMS to reference each track.