remix-validated-form icon indicating copy to clipboard operation
remix-validated-form copied to clipboard

[Feature]: Convert formData paths to a nested JS object

Open aniravi24 opened this issue 2 years ago • 3 comments

What is the new or updated feature that you are suggesting?

Currently, useFormContext allows you to grab the values with getValues. However, this returns formData, and converting it to a JS object gives you a flat object with the keys of the object displayed with the name as shown in the "Arrays as Objects" section here in the documentation.

Our use case is that we need to be able to pull out the values being entered within a nested field because we need to show a total in the UI of what's being entered to help users balance debits and credits (accounting stuff). We'd like to show this in real-time, and we want it to be displayed regardless of whether it's an error (i.e. even if it's valid, it should still show the numbers/totals).

Why should this feature be included?

The library already seems to do this internally with objectFromPathEntries, and it would be nice to have a version of that which is exported in the form context. This would help us display information on the page in real-time. It would also be nice to have a JS-based representation of the data that's easily accessible so we don't have to hack around the library to try to get this information out of FormData and depend on the form's internal representation of that information.

aniravi24 avatar Nov 29 '22 21:11 aniravi24

Hi!

I think it's a good idea to expose the objectFromPathEntries api so you can use it with getValues. If you happen to be using zod-form-data, that already exports a preprocessFormData helper that does exactly this (looks like we need to document this).

This approach won't get you reactivity though -- it only works to get the values imperatively. To make this work reactively you'll want useControlField. If you have a controlled field at foo.bar[0] and you call useControlField("foo"), then you'll get back the whole nested object ({ bar: ['somevalue'] }).

Here's an example of how to implement something kinda like the use-case you're describing: https://www.remix-validated-form.io/reference/use-control-field.

If you have a lot of these use-cases in your project, you might consider following the "Globally tracking / updating all fields" example in the doc I linked above.

airjp73 avatar Nov 30 '22 13:11 airjp73

Will take a look, thank you!

aniravi24 avatar Dec 12 '22 21:12 aniravi24

I was reading this issue. Maybe this is related: https://github.com/airjp73/remix-validated-form/issues/232.

superjose avatar Jan 11 '23 08:01 superjose

RVF v6 has been released 🎉

In v6 form.value() returns a structured object, rather than form data. If that still doesn't quite cover this use-case, please feel free to open a new issue.

You can find the documentation here and the migration guide here.

airjp73 avatar Aug 08 '24 20:08 airjp73