-1

So I'm not sure why this piece of code isn't working. What I have is an array of file types the component accepts. I try to iterate over the that array and check if the file being uploaded is of one of those types. If it is NOT then I return;. For some reason the code below acceptedFormats.forEach continues to run. If I console.log the audioType and file.type I get an INVALID for each. So again shouldn't it be returning? Thanks!

class Upload extends React.Component {
          state = {
            percentage: 0,
            uploading: false
          }
          handleUpload = (e) => {
            if (this.state.uploading) {
              return;
            }
            const file = e.target.files[0];
            const acceptedFormats = ["audio/wav", "audio/mp3", "audio/m4a"];
            
            // TODO: Figure out why this isn't working
            acceptedFormats.forEach((audioType) => {
              console.log(audioType);
              console.log(file.type);
              if(audioType !== file.type) {
                console.log('INVALID');
                return;
              }
            })
        
            const audioRef = storageRef.child('audio/' + file.name);
            const task = audioRef.put(file);
        
            task.on('state_changed', function(snapshot){
              const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
              console.log('Upload is ' + progress + '% done');
              this.setState(() => ({
                percentage: progress
              }))
            }.bind(this), function(error) {
        
            }, function() {
              const downloadURL = task.snapshot.downloadURL;
              const fileName = task.snapshot.metadata.name;
              let songName = removeFileExtension(file.name);
              songName.replace(/\./g,' ');
        
              db.ref(`users/${this.props.uid}/uploadedSongs/`).push({
                downloadURL,
                fileName,
                songName,
              }).then(() => {
                this.setState({
                  percentage: 0,
                  uploading: false
                })
                Alert.success(`Upload successful`, {
                  position: 'top-right',
                  effect: 'slide',
                  timeout: 3000
                })
              })
            }.bind(this));
          }
          render() {
            return (
              <div className="Upload">
                <label className={this.state.uploading ? "Upload__button-disabled btn" : "Upload__button btn"}>
                  <span className="Upload__button-text">{this.state.uploading ? "Uploading" : "Upload a song"}</span>
                  <input className="Upload__input" type="file" onChange={(e) => this.handleUpload(e)} disabled={this.state.uploading ? true : false}/>
                </label>
                <span style={{color: '#808080', fontSize: '12px'}}>Accepted formats: .wav, .mp3, .m4a</span>
              </div>
            );
          }
        }
        
ReactDOM.render(<Upload />, document.querySelector('#u'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.0/react-dom.min.js"></script>


<h1>Example Upload</h1>
<div id="u"></div>
styfle
  • 22,361
  • 27
  • 86
  • 128
maxwellgover
  • 6,661
  • 9
  • 37
  • 63
  • 1
    I don't follow this: "If I console.log the audioType and file.type I get an INVALID for each." Logging those things won't return "INVALID". Are you trying to say that you get inside that `if(audioType !== file.type)` block? – jmargolisvt Aug 07 '17 at 01:10
  • is this a pure Javascript? Does Javascript accept keyword `extends` just like what you're doing now? Do you want to return a value or just stop the process? – smzapp Aug 07 '17 at 01:10
  • I cleaned it up so its runnable...this is clearly React.js so I added the tag – styfle Aug 07 '17 at 01:16
  • Possible duplicate of [How to short circuit Array.forEach like calling break?](https://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break) – styfle Aug 07 '17 at 01:19

1 Answers1

2

return within .forEach() callback does not prevent futher code outside the scope of .forEach() callback to run. You can use .some() which returns a Boolean true or false and an if condition and statement to return if true is returned from .some() call

  if (acceptedFormats.some(audioType => {
      console.log(audioType);
      console.log(file.type);
      return audioType !== file.type
  })) {
      console.log('INVALID');
      return;
  }
guest271314
  • 1
  • 15
  • 104
  • 177