inertiajs / inertia

Inertia.js lets you quickly build modern single-page React, Vue and Svelte apps using classic server-side routing and controllers.
https://inertiajs.com
MIT License
6.02k stars 405 forks source link

[React] Use updater function in `setData` in `useForm` hook #1859

Closed rrmesquita closed 2 weeks ago

rrmesquita commented 2 months ago

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 commented 2 months ago

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.

reinink commented 2 weeks ago

@rrmesquita Hey thanks for catching this! 🙏

And thanks for the review @derrickreimer and @thecrypticace 🤙

FrozenGod commented 2 days ago

Just upgraded to 1.2.0 with hope that it'll be fixed but it seems to still be bugged.

derrickreimer commented 2 days ago

This patch is not released yet, but will go out in the next version.