wsmd/react-use-form-state

[feature request] Array field support

melloc01 opened this issue · 2 comments

Let's say you have a field that is named: Requests:

type Requests = Array<{url: string, name: string}>

Is there a way to do something like this natively with the lib?

Of course, there are workarounds using 2 levels of formState:

  • Create one formState per row and add a global onChange listener to change the formState above
  • Use raw so you can trigger onChange manually for the above formState - this way you lose local validation

I feel the lib could support these cases natively

Thanks in advance

wsmd commented

Hi @melloc01!

I'm not exactly sure what your use case is. If possible, please provide code snippets or a live example to help me better understand this limitations (e.g. codesandbox).

It sounds like .raw() might be what you need here. It was introduced to handle this type of inputs that can have any shape.

For example, if you provide a custom component that controls Requests, you can treat all data related to Requests as a single unit/input in the form state (even though it can be represented as multiple inputs in the UI).

const Requests = ({ onChange, validate, value }) => {
  // maintaining the requests state independently
  const [requests, setRequests] = useState(value);
  const handleChange = useCallback((data) => {
    // update the requests data how like
    onChange(requests); // calling the input's onChange to update formState
  });
  return (
    // logic to render and update the requests fields
  );
}

const Form = () => {
  const [formState, { text, raw }] = useFormState({ requests: [] });
  return (
    <>
      <input {...text('name')} />
      <Requests {...raw('requests')} formState={formState} />
    </>
  );
};

Keep in mind that validation errors can be anything (an object or an array) which will be useful if you want to have multiple errors for a single input.

I hope that helps.

That's cool, solved it. thanks @wsmd and sorry for the late reply.