Jonas
Jonas

Reputation: 355

React Native: Using props in const

I'm new to react/react native and trying to build a simple app that plays local MP3. I'm using the react-native-sound module which seems to work really well.

Though now, I'm trying to pass fileName as props from my category to the player component. It seems like that react-native-sound requires me preload a sound file. Thus, now I get the following error:

"Unhandled JS Exception: Cannot read property 'fileName' of undefined".

...    
import Sound from 'react-native-sound';

const play = new Sound(this.props.fileName, Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
  } else { // loaded successfully
    console.log('duration in seconds: ' + play.getDuration() +
        'number of channels: ' + play.getNumberOfChannels());
  }
});

export default class playTrack extends Component {
    constructor(props) {
      super(props);
      this.state = {
        playing: false,
        track: this.props.fileName,
      };
    }

    playTrack() {
      this.setState({playing: true})
      play.play((success) => {
        if (success) {
          console.log('successfully finished playing');
        } else {
          console.log('playback failed due to audio decoding errors');
        }
      })
    }
...

Do you have any pointers for me how to go about this?

Upvotes: 2

Views: 4137

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

You don't have access to your class instance's this from outside the class the way you are trying to use it. Instead, create the Sound in the constructor:

import Sound from 'react-native-sound';

export default class playTrack extends Component {
    constructor(props) {
        super(props);

        this.play = new Sound(props.fileName, Sound.MAIN_BUNDLE, (error) = > {
            if (error) {
                console.log('failed to load the sound', error);
            } else { // loaded successfully
                console.log('duration in seconds: ' + this.play.getDuration() +
                    'number of channels: ' + this.play.getNumberOfChannels());
            }
        });

        this.state = {
            playing: false,
            track: this.props.fileName,
        };
    }

    playTrack() {
        this.setState({
            playing: true
        })
        this.play.play((success) = > {
            if (success) {
                console.log('successfully finished playing');
            } else {
                console.log('playback failed due to audio decoding errors');
            }
        })
    }

Upvotes: 2

Related Questions