Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduces "mapState" createField option #369

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/fields/Input.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react'
import PropTypes from 'prop-types'
import { createField, fieldPresets } from 'react-advanced-form'

class Input extends React.Component {
export class PlainInput extends React.Component {
static propTypes = {
/* General */
id: PropTypes.string,
Expand Down Expand Up @@ -75,4 +75,4 @@ class Input extends React.Component {
}
}

export default createField(fieldPresets.input)(Input)
export default createField(fieldPresets.input)(PlainInput)
57 changes: 57 additions & 0 deletions examples/full/ReduxIntegration/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
import { Form, createField, fieldPresets } from 'react-advanced-form'
import { PlainInput } from '@examples/fields/Input'
import { setVatRequired } from './reducers/actions'
import vatReducer from './reducers/vatReducer'

const store = createStore(vatReducer)

const RafInput = createField({
...fieldPresets.input,
mapState: (state, props) => [
{
required: props.isVatRequired,
},
['isVatRequired'],
],
})(PlainInput)

const SubscribedInput = connect((state) => ({
isVatRequired: state.isVatRequired,
}))(RafInput)

const RegistrationForm = (props) => {
const { setVatRequired, isVatRequired } = props

return (
<Form onSubmitStart={console.log}>
<SubscribedInput name="vatNumber" label="VAT" />

<button type="button" onClick={() => setVatRequired(!isVatRequired)}>
Toggle VAT required
</button>
<button type="submit">Submit</button>
</Form>
)
}

const WrappedRegistrationForm = connect(
(state) => ({
isVatRequired: state.isVatRequired,
}),
{ setVatRequired },
)(RegistrationForm)

class ReduxIntegration extends React.Component {
render() {
return (
<Provider store={store}>
<WrappedRegistrationForm />
</Provider>
)
}
}

export default ReduxIntegration
8 changes: 8 additions & 0 deletions examples/full/ReduxIntegration/reducers/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const SET_VAT_REQUIRED = 'SET_VAT_REQUIRED'

export const setVatRequired = (nextValue) => ({
type: SET_VAT_REQUIRED,
payload: {
nextValue,
},
})
3 changes: 3 additions & 0 deletions examples/full/ReduxIntegration/reducers/initialState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
isVatRequired: false,
}
12 changes: 12 additions & 0 deletions examples/full/ReduxIntegration/reducers/vatReducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import initialState from './initialState'
import * as actions from './actions'

export default function vatReducer(state = initialState, action) {
switch (action.type) {
case actions.SET_VAT_REQUIRED:
return { isVatRequired: action.payload.nextValue }

default:
return state
}
}
6 changes: 6 additions & 0 deletions examples/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ storiesOf('Behavior', module).add(
)

/* Basics */
import ReduxIntegration from './full/ReduxIntegration'
storiesOf('Redux integration', module).add(
'Redux',
addComponent(<ReduxIntegration />),
)

storiesOf('Basics|Interaction', module)
.add('Field unmounting', addComponent(<FieldUnmounting />))
.add('Initial values', addComponent(<InitialValues />))
Expand Down
60 changes: 60 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,11 @@
"react-datepicker": "^2.0.0",
"react-dom": "^16.6.3",
"react-rangeslider": "^2.2.0",
"react-redux": "^6.0.1",
"react-select": "^2.1.2",
"react-slider": "^0.11.2",
"recompose": "^0.30.0",
"redux": "^4.0.1",
"regenerator-runtime": "^0.12.1",
"rimraf": "^2.6.2",
"start-server-and-test": "^1.7.11",
Expand Down
11 changes: 11 additions & 0 deletions src/components/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,17 @@ export default class Form extends React.Component {
nextFields: updatedFields,
})

/**
* @todo Remove this.
* Force update of the updated field.
* When a field component is wrapped in another HoC, the latter
* may block the field's update caused by form's state update.
* To ensure form state update always results into fields update
* there is this force.
*/
const fieldRef = nextFieldState.getRef()
fieldRef.forceUpdate()

resolve(updatedFields)
})
} catch (error) {
Expand Down
33 changes: 31 additions & 2 deletions src/components/createField.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ const defaultOptions = {
enforceProps() {
return {}
},
mapState: (state, props) => {
return [{}, []]
},
mapValue(nextValue) {
return nextValue
},
Expand Down Expand Up @@ -165,6 +168,13 @@ export default function connectField(options) {
onBlur: prunedProps.onBlur,

/* Internal methods */
getNextState: (fieldState, props = this.props) => {
const [nextState, propSubscriptions] = hocOptions.mapState(
fieldState,
props,
)
return [R.mergeDeepLeft(nextState, fieldState), propSubscriptions]
},
mapValue: hocOptions.mapValue,
assertValue: hocOptions.assertValue,
serialize: hocOptions.serialize,
Expand Down Expand Up @@ -201,6 +211,7 @@ export default function connectField(options) {

componentWillReceiveProps(nextProps) {
const { props: prevProps, contextProps } = this

if (!contextProps) {
return
}
Expand Down Expand Up @@ -236,6 +247,24 @@ export default function connectField(options) {
fieldProps: contextProps,
})
}

/**
* @todo Remove this.
* Temporary solution to be able to derive field's state from the
* prop injected by high-order components (i.e. Redux).
*/
const [nextFieldState, subscribedProps] = contextProps.getNextState(
recordUtils.resetValidityState(contextProps),
nextProps,
)

if (
subscribedProps.some(
(propName) => !R.equals(prevProps[propName], nextProps[propName]),
)
) {
this.context.form.updateFieldsWith(nextFieldState)
}
}

/**
Expand Down Expand Up @@ -366,15 +395,15 @@ export default function connectField(options) {

render() {
const { props, contextProps } = this

/* Render null and log warning in case of formless field */
if (!contextProps) {
warning(
false,
'Failed to render the field `%s`: expected to be a child ' +
'of a Form component. Please render fields as children of ' +
'Form, since formless fields are not currently supported.',
this.__fieldPath.join('.'),
this.__fieldPath.join('.'),
)
return null
}
Expand Down
12 changes: 10 additions & 2 deletions src/utils/recordUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ export const createField = (initialState) => {
const valuePropName = initialState.valuePropName || 'value'
const value = initialState[valuePropName]

return {
const getNextState =
initialState.getNextState ||
function(state) {
return [state]
}

const [fieldState] = getNextState({
/* Internal */
fieldGroup: null,
fieldPath: null,
Expand Down Expand Up @@ -61,7 +67,9 @@ export const createField = (initialState) => {
onBlur: null,

...initialState,
}
})

return fieldState
}

/**
Expand Down