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

[feature request] Array field support #71

Closed
melloc01 opened this issue May 7, 2019 · 2 comments
Closed

[feature request] Array field support #71

melloc01 opened this issue May 7, 2019 · 2 comments

Comments

@melloc01
Copy link

melloc01 commented May 7, 2019

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
Copy link
Owner

wsmd commented May 14, 2019

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.

@wsmd wsmd closed this as completed May 14, 2019
@melloc01
Copy link
Author

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

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

No branches or pull requests

2 participants