buildo/formo

Support fieldProps alone without the need to define validators or onSubmit

Opened this issue · 5 comments

The use case is when you just need fieldProps but you don't need validation or submit functionality. For example when you don't have a standard form and you just want an easy way to have name, value, onChange, onBlur defined.

So my proposal is to have something like this code below.
This is thought to be used with the useState so you can pass to fieldProps directly what useState returns.

  const fieldProps = <A, B extends keyof A>(
    field: B,
    model: [A, (val: A) => void]
  ): {
    name: B;
    value: A[B];
    onChange: (val: A[B]) => void;
    onBlur: () => void;
  } => ({
    name: field,
    value: model[0][field],
    onChange: (val) => {
      model[1]({
        ...model[0],
        [field]: val,
      });
    },
    onBlur: () => {},
  });

This is thought to be used with the useState so you can pass to fieldProps directly what useState returns.

What about using the internal formo state directly instead? e.g.:

const fieldProps = useFieldProps({ ...initialValues });

Do you see any pros/cons?

The only "problem" I see is that sometimes you don't need a state because for example the state is handled by a parent component that inject to you a value and an onChange prop using your component as a kind of field itself. Anyway, it's ok to have another state handled by formo and kept in sync with the parent.

Got it, makes sense, maybe we could also ask you implement an (optional?) onChange (other than the initial value) so that it can be implemented by forwarding to the parent when needed. Which is basically what you are proposing with a slightly different API

Yes, it seems perfect! 💯

So I believe this could be a good signature:

export function useFieldProps<Values extends Record<string, unknown>, Label>(args: {
  initialValues: FormOptions<Values, {}, {}, never>[0]['initialValues'],
  onChange?: (values: Values) => void
}): UseFormReturn<Values, never, Label, never>['fieldProps']