dvdzkwsk / react-reformed

Make React forms simple again, see it here:
https://react-reformed.zuko.me/
MIT License
541 stars 32 forks source link

How to implement "middleware"? #20

Closed tgoorden closed 6 years ago

tgoorden commented 6 years ago

I would sort of expect this to work, but it doesn't. Any idea what I might be doing wrong?

const middleware = (props) => {
  const { setModel, setProperty, ...xProps } = props
  const interceptedSetModel = (model)=> {
    console.log(model)
    return setModel(model)
  }
  const interceptedSetProperty = (name,value) => {
    console.log(value)
    return setProperty(name,value)
  }
  return { setModel: interceptedSetModel, setProperty: interceptedSetProperty, ...xProps }
}

const SimpleForm = props => {
  const { bindInput } = props
  return (
    <form>
      <Input {...bindInput('example')} />
    </form>
  )
}

const ReformedForm = reformed(middleware)(SimpleForm)

ReactDOM.render(<ReformedForm />, document.getElementById('app'))

There are no (expected) logs when the model inside the reformed form changes. I'm really stumped...

dvdzkwsk commented 6 years ago

Ah, I see how this is confusing (and it's definitely unintentional). I'll have to look into the best way to patch this, but the issue is that bindInput is still referring to the internal setProperty instead of the one you supplied. See: https://github.com/davezuko/react-reformed/blob/master/src/reformed.js#L34-L47.

You would likely see the correct behavior if you supplied onChange and value directly to the input. I'll take a look at the internals a bit today to see if there's an easy fix.

dvdzkwsk commented 6 years ago

Fixed with #21. It's not the most ideal fix, since it re-creates two functions on each render, but it's the only reliable solution I could come up with. It's technically a breaking change because we can no longer provide bindInput and bindToChangeEvent to the middleware function.

You should be able to pull v2.0.0 and see it working. I've put together an example here: https://codesandbox.io/s/p319vx87wm.

tgoorden commented 6 years ago

Oh wow, thank you. I though I was going crazy there for a second ;)

Thank you for this fix, it seems to work as expected!