Skip to content

Commit

Permalink
Fix the register function
Browse files Browse the repository at this point in the history
Context: When two or more Fields are used either inside the Conditional component or both
in their own Conditional with the same show condition, only the last
Field receive its initial value set in item attribute via Formol
component.

The cause: when a Field is mounted, the register function is executed to
register the component in transientItem variable. But due to the async
nature of setState, the transientItem between Fields registration stays
the same.

I think this commit is an attempt to fix the bug c12d07c
But it seems to appear again #62
  • Loading branch information
Aro Andriamaro committed Mar 11, 2021
1 parent fe2f12b commit f5fe40a
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/Formol.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,18 +169,27 @@ export default class Formol extends React.PureComponent {
}

register(name, element, validator, validityErrors) {
const { item, transientItem } = this.state.context
const { item } = this.state.context
this.fields.names.push(name)
this.fields.elements[name] = element
this.fields.validators[name] = validator
this.fields.validityErrors[name] = validityErrors
// If field is added as a later date we might need to copy its item value
// if it's not present in transientItem
if (item[name] !== void 0 && item[transientItem] === void 0) {
this.setStateContext({
transientItem: { ...transientItem, [name]: item[name] },
})
}

this.setState(prevState => {
const { context: prevContext } = prevState
const { transientItem: prevTransientItem } = prevContext

const newState = item.hasOwnProperty(name)
? {
context: {
...prevContext,
transientItem: { ...prevTransientItem, [name]: item[name] },
},
}
: { context: { ...prevContext } }

return newState
})
}

unregister(name) {
Expand Down

0 comments on commit f5fe40a

Please sign in to comment.