0

today I tried to pass the setState function to a util function and got a different result on how to pass it. I would like to know why exactly this makes a different.

I have a method like this:

function handleChange(setState) {
  setState(oldState => { ... oldState, ... someNewAttributes}
}

It gives me an error ("TypeError: Cannot read property 'updater' of undefined") when I try to pass it like this:

handleChange(this.setState);

But works like a charm if I pass it wrapped in a lamba:

handleChange((x) => this.setState(x));

Can someone explain this with the Javascipt mechanics, why this makes a difference?

markusw
  • 1,840
  • 13
  • 27
  • 1
    The first way loses the context of `setState`. The second preserves it. You can also pass `this.setState.bind(this)` but IMO looks odd. – VLAZ Jul 04 '19 at 13:10
  • Not a duplicate, since the this is actually the correct one in the above example, the second one actually loses the context and should not work. Maybe an inside of react mechanics are also necessary – markusw Jul 04 '19 at 13:13
  • 1
    Why do you think the first one is correct and the second one loses context…? – deceze Jul 04 '19 at 13:15
  • @markusw please read the linked dupe. What you are saying is *not* how JS works. – VLAZ Jul 04 '19 at 13:16

0 Answers0