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

[React] Use updater function for key-value data setter in useForm hook #1859

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

rrmesquita
Copy link

This is a proposal for changing the ergonomics of the key-value variant for the setData hook in React.

Current behaviour

Using this simple form as an example:

const form = useForm({
    name: 'Alice',
    lastname: 'Doe',
})

It is expected that sequential calls to setData will update the form data accordingly. However, subsequent calls overwrite the changes made by the previous calls.

form.setData('name', 'Bob') // { name: 'Bob', lastname: 'Doe'}
form.setData('lastname', 'Smith') // { name: 'Alice', lastname: 'Smith'}

Desired behaviour

Sequential setData calls use an updater function to batch the changes from multiple calls.

form.setData('name', 'Bob') // { name: 'Bob', lastname: 'Doe'}
form.setData('lastname', 'Smith') // { name: 'Bob', lastname: 'Smith'}

This can be achieved using updater functions for the set functions in React. From React documentation:

Is using an updater always preferred?

In most cases, there is no difference between these two approaches.

However, if you do multiple updates within the same event, updaters can be helpful.

If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state.

It is worth noting that this only affects the key-value variant of the setData function, and if anyone is impacted by this change, they can switch to the object variant of the setData function.

@rrmesquita rrmesquita changed the title Use set function for key-value data setter in useForm react hook Use updater function for key-value data setter in useForm react hook Apr 18, 2024
@rrmesquita rrmesquita changed the title Use updater function for key-value data setter in useForm react hook [React] Use updater function for key-value data setter in useForm hook Apr 18, 2024
@rrmesquita
Copy link
Author

Update: I just noticed that the current behaviour is very unexpected because it overrides previous changes not only from key-value calls but all setData calls. Personally, I consider this a bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant