Comments (5)
OK, since this was making me itch, I've figured out a way that is potentially more elegant.
Essentially, setModel
, setProperty
and the binding are all hooked into the state
somehow. This implies that intercepting one would basically force you to intercept all. Otherwise, there is no way of keeping the (model) state predictable, without terribly complex code.
So, the solution seems to abstract out the model state handling instead. In fact, in all likelihood this is what any middleware is interested in anyway. The rest is solvable on a (form) component level.
I've reworded reformed.js
to reflect this approach. The middleware can (in this system) intercept setModel
, getModel
and/or setModelValue
and getModelValue
. For instance a validator would be able to work with setModelValue
to mark dirty fields, etc.
Incidentally, it seems to me that it would make sense to do all this in the constructor instead of the render
function, no?
import React from 'react'
import PropTypes from 'prop-types'
import assign from 'object-assign'
import hoistNonReactStatics from 'hoist-non-react-statics'
const makeWrapper = (middleware) => (WrappedComponent) => {
class FormWrapper extends React.Component {
static propTypes = {
initialModel: PropTypes.object,
}
constructor (props, ctx) {
super(props, ctx)
this.state = {
model: props.initialModel || {},
}
class ModelHandlerWrapper {
constructor({getState,setState}) {
this.getState = getState
this.setState = setState
}
setModel = (model) => {
this.setState({model})
return model
}
getModel = ()=> getState("model")
getModelValue = (name)=> this.getModel()[name]
setModelValue = (name,value)=> {
return this.setModel(assign({}, this.getModel(), {
[name]: value,
}))
}
}
const getState = (name) => this.state[name]
this.modelHandler = new ModelHandlerWrapper({getState: getState, setState: this.setState.bind(this)})
if (typeof middleware === 'function') {
this.modelHandler = middleware(this.modelHandler)
}
}
setModel = (model) => {
return this.modelHandler.setModel(model)
}
setProperty = (prop, value) => {
return this.modelHandler.setModelValue(prop,value)
}
// This, of course, does not handle all possible inputs. In such cases,
// you should just use `setProperty` or `setModel`. Or, better yet,
// extend `reformed` to supply the bindings that match your needs.
bindToChangeEvent = (e) => {
const { name, type, value } = e.target
if (type === 'checkbox') {
const oldCheckboxValue = this.modelHandler.getModelValue(name) || []
const newCheckboxValue = e.target.checked
? oldCheckboxValue.concat(value)
: oldCheckboxValue.filter(v => v !== value)
this.setProperty(name, newCheckboxValue)
} else {
this.setProperty(name, value)
}
}
bindInput = (name) => {
return {
name,
value: this.modelHandler.getModelValue(name) || '',
onChange: this.bindToChangeEvent,
}
}
render () {
let nextProps = assign({}, this.props, {
model: this.modelHandler.getModel(),
setProperty: this.setProperty,
setModel: this.setModel,
bindInput: this.bindInput,
bindToChangeEvent: this.bindToChangeEvent
})
return React.createElement(WrappedComponent, nextProps)
}
}
FormWrapper.displayName = `Reformed(${getComponentName(WrappedComponent)})`
return hoistNonReactStatics(FormWrapper, WrappedComponent)
}
const getComponentName = (component) => (
component.displayName ||
component.name
)
export default makeWrapper
from react-reformed.
Yeah, I'd realized the patch wouldn't affect setModel
, but didn't think it should be necessary because it's an implementation detail of setProperty
; that is, the consumer shouldn't rely on setProperty
dispatching to setModel
.
I will read through your proposals when I get some time today, but wanted to get a quick response out. Thank you for the detailed post. If it's a clean enough solution we can consider it :).
from react-reformed.
I took a look at your proposal, and it seems pretty solid for your use case. I do have some reservations, though, mainly that the middleware function would only run once, at component instantiation time, which would break the expected function signature of Props -> Props
and restrict its overall utility.
At this point I'm wondering if this is something that middleware shouldn't even be responsible for, since the only reliable way to update function references after applying middleware is to have them rely on this
, but that presents its own set of problems. For what it's worth, middleware at the top-level wasn't something I'd ever really intended to be a core part of the API, but was added mainly as an easy escape hatch.
I would really like to solve for this though, so I'm continuing to play around with a few ideas on my end. If this is blocking you, though, please feel free to fork this project in the meantime :).
from react-reformed.
Yes, I agree that it's an interesting (architectural) challenge. To be honest I'm not familiar enough with the React lifecycle and it's architectural consequences to make a good estimate here. However, it seems to me that it wouldn't be too hard to use this approach inside of the "render" cycle. I guess you would end up with some kind of generator functionality like you wrote before for the bindInput
function, but this time with a "model handler" as its argument instead of setProperty
.
The current code is quite tied into this
to be able to do this without a significant rewrite so I ended up taking the easy way out, which meant doing it at constructor time.
from react-reformed.
OK, this seems to work fine and it allows the middleware to jump in during the render
cycle:
You might note that I'm using set
and get
from lodash to allow "dotted" property names to be used, with a correct translation into an object structure. This adds a lot of extra functionality IMO.
import React from 'react'
import PropTypes from 'prop-types'
import assign from 'object-assign'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { set, get } from 'lodash'
class ModelHandlerWrapper {
constructor({getState,setState}) {
this.getState = getState
this.setState = setState
}
setModel = (model) => {
this.setState({model})
return model
}
getModel = ()=> this.getState("model")
getModelValue = (name)=> get(this.getModel(),name)
setModelValue = (name,value)=> {
return this.setModel(set(this.getModel(),name,value))
}
}
const makeWrapper = (middleware) => (WrappedComponent) => {
class FormWrapper extends React.Component {
static propTypes = {
initialModel: PropTypes.object,
}
constructor (props, ctx) {
super(props, ctx)
this.state = {
model: props.initialModel || {},
}
}
makeHelpers = (modelHandler) => {
bindToChangeEvent = (e) => {
const { name, type, value } = e.target
if (type === 'checkbox') {
const oldCheckboxValue = modelHandler.getModelValue(name) || []
const newCheckboxValue = e.target.checked
? oldCheckboxValue.concat(value)
: oldCheckboxValue.filter(v => v !== value)
modelHandler.setModelValue(name, newCheckboxValue)
} else {
modelHandler.setModelValue(name, value)
}
}
helpers = {
setModel: (model) => modelHandler.setModel(model)
,
setProperty: (prop, value) => modelHandler.setModelValue(prop,value)
,
bindToChangeEvent: (e) => {
const { name, type, value } = e.target
if (type === 'checkbox') {
const oldCheckboxValue = modelHandler.getModelValue(name) || []
const newCheckboxValue = e.target.checked
? oldCheckboxValue.concat(value)
: oldCheckboxValue.filter(v => v !== value)
modelHandler.setModelValue(name, newCheckboxValue)
} else {
modelHandler.setModelValue(name, value)
}
}
,
bindInput: (name) => {
return {
name,
value: modelHandler.getModelValue(name) || '',
onChange: bindToChangeEvent,
}
}
}
return helpers
}
render () {
const getState = (name) => this.state[name]
let modelHandler = new ModelHandlerWrapper({getState: getState, setState: this.setState.bind(this)})
if (typeof middleware === 'function') {
modelHandler = middleware(modelHandler)
}
let nextProps = assign({}, this.props, {
model: modelHandler.getModel()
},
this.makeHelpers(modelHandler)
)
return React.createElement(WrappedComponent, nextProps)
}
}
FormWrapper.displayName = `Reformed(${getComponentName(WrappedComponent)})`
return hoistNonReactStatics(FormWrapper, WrappedComponent)
}
const getComponentName = (component) => (
component.displayName ||
component.name
)
export default makeWrapper
from react-reformed.
Related Issues (12)
- Validation should take keep track of dirtyness HOT 3
- UMD release HOT 3
- Deprecation warning about PropTypes HOT 3
- Question regarding Complex validation based on state of the model
- I implemented a reformed component in Typescript. HOT 1
- Question regarding this vs. redux-form HOT 5
- How to implement "middleware"? HOT 3
- Question regarding patterns with autofill and server rendering HOT 6
- How to implement isSubmiting HOT 2
- Suggestion to support updating nested properties HOT 1
- Forms without initial model cause React warning message HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-reformed.