1

I'm using React and inside my componentDidMount() {} I'm calling an imported function and want to access this.setState within it.

Within componentDidMount, When I console.log(this), I get the component as expected.

But if I run myFunction.call(this), console.log(this) inside myFunction returns undefined.

Any ideas why this is not being passed correctly?

edit1: adding code.

Component:

class Navbar extends React.Component {
    componentDidMount() {
        myFunction.call();
    }
}

myFunction.js:

export const myFunction = () => {
    console.log('this:', this);
}

Console output:

this: undefined

edit2: some people flagged this as a duplicate of "can i bind arrow functions" but myFunction is an arrow function and even if I call it directly instead of using .call() it produces the same result: this is undefined.

Mark Jackson
  • 3,218
  • 3
  • 28
  • 29

1 Answers1

1

Bind the imported function in the constructor:

import { myFunction } from './path/to/myFunction';

class Navbar extends React.Component {
    constructor() {
       /* other constrcutor code */
       myFunction = myFunction.bind(this);
    }
    componentDidMount() {
       myFunction();
    }
}

In your myFunction.js, convert the ES6 arrow function to a regular ES5 function (see Can you bind arrow functions?):

export const myFunction = function() {
    console.log('this:', this);
}
connexo
  • 49,059
  • 13
  • 74
  • 108