1

I have a function that sits in one of my React components that's starting to get a bit long. I've decided to keep it in a separate file to keep my component a bit tidier. The issue is that the component has to refer to this in order to get functions and states that are mapped to the props through Redux. Here's how I call it in my component:

import {myFunction} from './functions/myFunction';

handleMyFunction(event) {
    myFunction(event).bind(this)
}

componentDidMount() {
    this.handleMyFunction()
}

Here is the function itself in './functions/myFunction':

export const captureSnapshot = (event) => {
    console.log(this.props.someState)
}

I would have thought that bind this would make all the props available in the imported function but instead I get:

Cannot read property 'props' of undefined

when I try to run the function. How can I pass "this" to the function properly?

red house 87
  • 1,837
  • 9
  • 50
  • 99
  • You are trying to access and call `.bind` on the **return value** of `myFunction`. `myFunction(event)` resolves to the return value of `myFunction`. – Felix Kling Oct 31 '17 at 16:44

1 Answers1

1

You can't use bind in function execution

this line is wrong

myFunction(event).bind(this)

instead use apply or call

example myFunction.call(this , event) or myFunction.apply(this , [event])

You can learn more about the difference between 'bind', 'call', and 'apply' in this answer

Also one more edit you might have this function handleMyFunction with incorrect this context as well so change it to

handleMyFunction = (event) => {
    myFunction.call(this , event)
}
Amr Labib
  • 3,995
  • 3
  • 19
  • 31
  • I tried both of your methods and they're both giving me the exact same error message! – red house 87 Oct 31 '17 at 16:52
  • can you `console.log(this.props.someState)` before calling the function and check if this value exist , probably `handleMyFunction` does not have the correct `this` as well i updated the answer to use arrow function to be called with correct `this` context as well – Amr Labib Oct 31 '17 at 16:55
  • The issue was with me having an arrow function instead of just a normal one in myFunction.js. I changed it to a normal one and it had the right context, now works. Can you update your answer to reflect that please? – red house 87 Oct 31 '17 at 17:00