Euan
Euan

Reputation: 3

access state from within component class

I am new to react, I am trying to use state to replace native JS DOM calls update DOM from inside a method.
I can't seem to get it to work. It keeps saying this.setState is not a function.
this is my current code below:

class AddMsg extends React.Component {
  constructor(props) {
   super(props);
   this.state = {uploadBar: 'hide'};
  }
  ...
  handleSubmit(e) {
    ...
     if (file !== '' && this.state.chars_left >= 0) {
       ...
       uploadTask.on('state_changed', function (snapshot) {
         ...
        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        (progress < 100)
          ? this.setState({uploadBar: 'show'})
          : this.setState({uploadBar: 'hide'})
        }, function error(err) {
         ...
       }, function complete() {
         ... 
       }
       ...
  }
  render(){
    return(
      ...
      <span className={`help is-primary has-text-centered ${this.state.uploadBar}`}> Sending scribe now...</span>
    )
  }
}

the code I am trying to replace...

    (progress < 100)
      ? document.getElementById('uploadBar').style.display = 'block'
      : document.getElementById('uploadBar').style.display = 'none';

anyone got any suggestions?
Like I said I keep getting setState is not a function.

Upvotes: 0

Views: 66

Answers (2)

guitoof
guitoof

Reputation: 955

You can also use arrow function to widen the access scope of your callback function:

uploadTask.on('state_changed', (snapshot) => {
     ...
    let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    (progress < 100)
      ? this.setState({uploadBar: 'show})
      : this.setState({uploadBar: 'hide})
})

You also forgot the closing quotes after show and hide. I think you meant to write:

this.setState({uploadBar: 'show'})
this.setState({uploadBar: 'hide'})

Upvotes: 1

Davin Tryon
Davin Tryon

Reputation: 67336

You need to bind this callback:

uploadTask.on('state_changed', function (snapshot) {
    ...
}.bind(this));

Otherwise, you don't have the context where this.setState exists. Since the callback is called by something outside the current context, you must bind manually if you want this to resolve correctly.

Upvotes: 0

Related Questions