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.

remjx
  • 4,104
  • 3
  • 34
  • 32

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
  • 53,704
  • 14
  • 91
  • 128
  • when I do this it errors within the constructor saying myFunction is not defined – remjx Jun 20 '19 at 00:59
  • Well then clearly your import is either not there or it does not work. That, though, cannot be a result of my suggested changes. – connexo Jun 20 '19 at 05:49