jgoraya
jgoraya

Reputation: 151

Function Is Not Defined Error in React

I am trying to call a function from componentDidMount which sets the State but keep coming across an error of

Uncaught ReferenceError: setPanelState is not defined

Below is the code...

export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
     PATIENT: [],
     COMPPROPS: [],
    };

    this.setPanelState = this.setPanelState.bind(this);
  }

    setPanelState(activity) {
          this.setState({COMPPROPS: [{compName:'Overview', compState:'Edit'}]});
    }

    componentDidMount() {   
       //handles chat commands and if the command is update patient the Overview panel should change to editable
       this.directLine.activity$
        .filter(function (activity) {
          return activity.type === 'event' && activity.value === 'Update Patient';
       })
       .subscribe(function (activity) {
         setPanelState(activity);   
       })
  }

I have tried make setPanelState a function outside of the class as opposed to a method but I get an error there as well.

Any thoughts?

Upvotes: 1

Views: 3521

Answers (4)

Yaniv Peretz
Yaniv Peretz

Reputation: 1168

change to

 this.setPanelState(activity)

at the end.

Upvotes: 0

ismnoiet
ismnoiet

Reputation: 4159

In your componentDidMount method call setPanelState using this.setPanelState

you can also use a better format:

.subscribe(this.setPanelState)

If you put setPanelState outside the class and call it, it won't work, unless it is defined inside another class where you can use setState.

Upvotes: 0

João Cunha
João Cunha

Reputation: 10297

Since you're using ES6 classes I assume you have it all set up.

Use arrow functions that bind this automatically

To learn more about arrow functions see this

.subscribe((activity) => {
    this.setPanelState(activity);   
})

Your component would look like this:

 export default class Patient extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);

    this.state = {
     PATIENT: [],
     COMPPROPS: [],
    };

    this.setPanelState = this.setPanelState.bind(this);
  }

    setPanelState(activity) {
          this.setState({COMPPROPS: [{compName:'Overview', compState:'Edit'}]});
    }

    componentDidMount() {   
       //handles chat commands and if the command is update patient the Overview panel should change to editable
       this.directLine.activity$
        .filter((activity) => {
          return activity.type === 'event' && activity.value === 'Update Patient';
       })
       .subscribe((activity) => {
         this.setPanelState(activity);   
       })
  }

Upvotes: 2

simbathesailor
simbathesailor

Reputation: 3687

Use this.setPanelState(activity) and remember to maintian the context .As you are non ES6 arraow function . save the context outside var that=this and access that variable inside

Upvotes: 0

Related Questions