1

I have a React.js component and I'd like to define a higher order method like so -

updater: function (path) {
  return function (value) {
    this.setState(this.modules.setter.set(this.state, path, value)) 
  }
}

Where this.modules.setter.set returns an updated version of the state, with a new value lying along the specified path.

This is in the hopes of being able to define a method like so -

updateUserStreet: this.updater('user.address.street')

I have no problem with creating the desired this.modules.setter.set, however I'm having trouble using a higher-order method in general. The console is telling me that this.updater is not a function

Any thoughts?

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • 1
    Is `updater` defined on the same object as `updateUserStreet`? If yes, this is a duplicate of [Self-references in object literal declarations](http://stackoverflow.com/q/4616202/218196) – Felix Kling Nov 24 '15 at 17:42
  • It is, though I think it might be worth leaving it as its own question since the answer is somewhat specific to React components and so would not be obvious from the answers to that question. That answer being - one should define these properties-defined-in-terms-of-other-properties in the .getInitialState method of the React Component. This solution is of the general flavor of the answers to the other question, which writ large involve giving the object a constructor function and defining those properties there. I could be wrong though, it just wasn't obvious to me... – user1050268 Nov 24 '15 at 18:57

2 Answers2

0

define updateUserStreet within the .getInitialState method of the React Component like so

getInitialState: function () {
  this.updateUserStreet = this.updater('user.address.street');
  return {...}
}

the updateUserStreet method will now be available within any other method defined on the React component

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0

Looks like updater is actually a reserved word in React components. It's used to maintain the component's lifecycle and state.

I couldn't find it in the docs directly, but found it mentioned briefly here: http://reactkungfu.com/2016/03/dive-into-react-codebase-handling-state-changes/

Try renaming updater to a different name.

Doug
  • 5,208
  • 3
  • 29
  • 33