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

[Form lib] Allow dynamic data to be passed to validator functions #109238

Merged
merged 5 commits into from
Aug 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
id: formLibCoreUseAsyncValidationData
slug: /form-lib/core/use-async-validation-data
title: useAsyncValidationData()
summary: Provide dynamic data to your validators... asynchronously
tags: ['forms', 'kibana', 'dev']
date: 2021-08-20
---

**Returns:** `[Observable<T>, (nextValue: T|undefined) => void]`

This hook creates for you an observable and a handler to update its value. You can then pass the observable directly to <DocLink id="formLibCoreUseField" section="validationData$" text="the field `validationData$` prop" />.

See an example on how to use this hook in the <DocLink id="formLibExampleValidation" section="asynchronous-dynamic-data-in-the-validator" text="asynchronous dynamic data in the validator" /> section.

## Options

### state (optional)

**Type:** `any`

If you provide a state when calling the hook, the observable value will keep in sync with the state.

```js
const MyForm = () => {
...
const [indices, setIndices] = useState([]);
// Whenever the "indices" state changes, the "indices$" Observable will be updated
const [indices$] = useAsyncValidationData(indices);

...

<UseField path="indexName" validationData$={indices$} />

}
```
12 changes: 12 additions & 0 deletions src/plugins/es_ui_shared/static/forms/docs/core/use_field.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,18 @@ If you provide a `component` you can pass here any prop you want to forward to t

By default if you don't provide a `defaultValue` prop to `<UseField />`, it will try to read the default value on <DocLink id="formLibCoreUseForm" section="defaultvalue" text="the form `defaultValue` object" />. If you want to prevent this behaviour you can set `readDefaultValueOnForm` to false. This can be usefull for dynamic fields, as <DocLink id="formLibExampleDynamicFields" text="you can see in the examples" />.

### validationData

Use this prop to pass down dynamic data to your field validator. The data is then accessible in the validator through the `customData.value` property.

See an example on how to use this prop in the <DocLink id="formLibExampleValidation" section="dynamic-data-inside-your-validation" text="dynamic data inside your validation" /> section.

### validationData$

Use this prop to pass down an Observable into which you can send, asynchronously, dynamic data required inside your validation.

See an example on how to use this prop in the <DocLink id="formLibExampleValidation" section="asynchronous-dynamic-data-in-the-validator" text="asynchronous dynamic data in the validator" /> section.

### onChange

**Type:** `(value:T) => void`
Expand Down
135 changes: 135 additions & 0 deletions src/plugins/es_ui_shared/static/forms/docs/examples/validation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,138 @@ export const MyComponent = () => {
```

Great, but that's **a lot** of code for a simple tags field input. Fortunatelly the `<ComboBoxField />` helper component takes care of all the heavy lifting for us. <DocLink id="formLibHelpersComponents" section="comboboxfield" text="Have a look at the example" />.

## Dynamic data inside your validation

If your validator requires dynamic data you can provide it through the `validationData` prop on the `<UseField />` component. The data is then available in the validator through the `customData.value` property.

```typescript
// Form schema
const schema = {
name: {
validations: [{
validator: ({ customData: { value } }) => {
// value === [1, 2 ,3] as passed below
}
}]
}
};

// Component JSX
<UseField path="name" validationData={[1, 2, 3]} />
```

### Asynchronous dynamic data in the validator

There might be times where you validator requires dynamic data asynchronously that is not immediately available when the field value changes (and the validation is triggered) but at a later stage.

Let's imagine that you have a form with an `indexName` text field and that you want to display below the form the list of indices in your cluster that match the index name entered by the user.

You would probably have something like this

```js
const MyForm = () => {
const { form } = useForm();
const [{ indexName }] = useFormData({ watch: 'indexName' });
const [indices, setIndices] = useState([]);

const fetchIndices = useCallback(async () => {
const result = await httpClient.get(`/api/search/${indexName}`);
setIndices(result);
}, [indexName]);

// Whenever the indexName changes we fetch the indices
useEffet(() => {
fetchIndices();
}, [fetchIndices]);

return (
<>
<Form form={form}>
<UseField path="indexName" />
</Form>

/* Display the list of indices that match the index name entered */
<ul>
{indices.map((index, i) => <li key={i}>{index}</li>)}
</ul>
<>
);
}
```

Great. Now let's imagine that you want to add a validation to the `indexName` field and mark it as invalid if it does not match at least one index in the cluster. For that you need to provide dynamic data (the list of indices fetched) which is not immediately accesible when the field value changes (and the validation kicks in). We need to ask the validation to **wait** until we have fetched the indices and then have access to the dynamic data.

For that we will use the `validationData$` Observable that you can pass to the field. Whenever a value is sent to the observable (**after** the field value has changed, important!), it will be available in the validator through the `customData.provider()` handler.

```js
// form.schema.ts
const schema = {
indexName: {
validations: [{
validator: async ({ value, customData: { provider } }) => {
// Whenever a new value is sent to the `validationData$` Observable
// the Promise will resolve with that value
const indices = await provider();

if (!indices.include(value)) {
return {
message: `This index does not match any of your indices`
}
}
}
}]
} as FieldConfig
}

// myform.tsx
const MyForm = () => {
...
const [indices, setIndices] = useState([]);
const [indices$, nextIndices] = useAsyncValidationData(); // Use the provided hook to create the Observable

const fetchIndices = useCallback(async () => {
const result = await httpClient.get(`/api/search/${indexName}`);
setIndices(result);
nextIndices(result); // Send the indices to your validator "provider()"
}, [indexName]);

// Whenever the indexName changes we fetch the indices
useEffet(() => {
fetchIndices();
}, [fetchIndices]);

return (
<>
<Form form={form}>
/* Pass the Observable to your field */
<UseField path="indexName" validationData$={indices$} />
</Form>

...
<>
);
}
```

Et voilà! We have provided dynamic data asynchronously to our validator.

The above example could be simplified a bit by using the optional `state` argument of the `useAsyncValidationData(/* state */)` hook.

```js
const MyForm = () => {
...
const [indices, setIndices] = useState([]);
// We don't need the second element of the array (the "nextIndices()" handler)
// as whenever the "indices" state changes the "indices$" Observable will receive its value
const [indices$] = useAsyncValidationData(indices);

...

const fetchIndices = useCallback(async () => {
const result = await httpClient.get(`/api/search/${indexName}`);
setIndices(result); // This will also update the Observable
}, [indexName]);

...
```
Loading