Josh
Josh

Reputation: 119

reactjs es6 calling function inside other function throws function not defined

Here is my code

In App.js file there is a button component. I am calling hi function onclick event. In this event, I want to use redux saga to call sayHello();

if I am using sayHello directly on button click event, code works fine. But my requirement is call it in an other function. Below is the entire file for reference.Appreciate your help.

Upvotes: 1

Views: 132

Answers (2)

AchinthaI
AchinthaI

Reputation: 41

When calling some function in another function, you have to specify the scope. Use it as below:

const hi = () => {
 console.log("hiiiiiiiiiiiiii");
 this.sayHello();
};

Hope this helps!

Upvotes: 1

xchunzhao
xchunzhao

Reputation: 46

You should defined ur function in your component scope.

Because the function SayHello is defined in props.

Just like this:

class App extends Component {

  hi = () => {
    onsole.log("hiiiiiiiiiiiiii");
    this.props.sayHello();
  }

  render() {
    const { hello, exampleTask } = this.props;
    return (
      <div className="App">
        <h1>Hello {hello}</h1>
        <h2>Redux-saga demo. Start editing to see some magic happen!</h2>
        <button onClick={this.hi}>Say Hello!</button>
        <button onClick={exampleTask}>Example Task</button>
      </div>
    );
  }
}


Upvotes: 0

Related Questions