react-nativereact-navigationreact-native-track-player

react-native-track-player error the player has already been initialized via setupPlayer


I have a react-navigation modal with react-native-track-player, closing one and opening it back throws the error The player has already been initialized via setupPlayer. How to make sure it runs only once? I couldn't find a method to do so.

useEffect(() => {
  setupPlayer();
}, []);

const setupPlayer = async() => {
  try {
    await TrackPlayer.setupPlayer();
    await TrackPlayer.updateOptions({
      capabilities: [
        Capability.Play,
        Capability.Pause,
        Capability.SkipToNext,
        Capability.SkipToPrevious
      ],
    });

    await TrackPlayer.add(podcasts);
    await gettrackdata();
    await TrackPlayer.play();
  } catch (error) {
    console.log(error);
  }
};


Solution

  • I made a function that runs once in App.js, and set a flag that can be later saved in context, store, or AsyncStorage if needed.

    async function isPlayerInitialized() {
      let isPlayerInitialized = false;
    
      try {
        await TrackPlayer.setupPlayer();
        await TrackPlayer.updateOptions({
          capabilities: [Capability.Play, Capability.Pause, Capability.SkipToNext, Capability.SkipToPrevious]
        });
    
        isPlayerInitialized = true;
      } catch (e) {
        // intentionally leaved as blank
      }
    }

    Thoughts: TrackPlayer is initialized only once, however, I don't like this approach because I have a feeling that there should be a specific method for checking if the TrackPlayer instance has already been set up.