This is the function
import { FormikHelpers } from 'formik';
import { v4 as uuid } from 'uuid';
import { Option } from '@pro4all/shared/ui';
export function splitAndAddToValues(
name: string,
value: string,
currentRecipients?: Option[],
setFieldValue?: FormikHelpers<unknown>['setFieldValue'],
setFieldTouched?: FormikHelpers<unknown>['setFieldTouched']
) {
if (!/[ ,;]/.test(value)) return;
// Return true if address already exists in field
const findDuplicate = (address: string) =>
currentRecipients.find((recipient) => recipient.inputValue === address);
// Remove duplicates from pasted text
const toUniqueArray = (addresses: string[]) => [...new Set(addresses)];
// Pasted text is parsed as addresses delimited by whitespace, semi colon or comma
const uniqueAddresses = toUniqueArray(
value
?.split(/[s;,]+/)
.filter(Boolean)
.filter((address) => !findDuplicate(address))
);
const nextRecipients: Option[] = uniqueAddresses.map((address) => ({
id: uuid(),
inputValue: address,
label: address,
}));
// Force the state updates to the form/components to the end of the browser's
// event loop.
setTimeout(() => {
// As long as we setValue() in a timed callback, the change triggered in the input will hide and clear autocomplete
setFieldValue(name, [...currentRecipients, ...nextRecipients]);
// Touch to trigger validation
setFieldTouched(name);
}, 0);
}
And this is the basic test.
import { splitAndAddToValues } from './splitAndAddToValues';
const name = 'admins';
const singleValue = '[email protected]';
const multipleValues = '[email protected] [email protected]';
test('Return one value if there is no comma, semicolon or space', () => {
expect(splitAndAddToValues(name, singleValue)).toHaveLength(2);
});
The problem is that if i call my fn with one value it returns undefined.
And if i call it with 2 values it tells me that the param address is not recognized, but the value is called below…
i don’t know if it is a hoisting problem
or a setTimeOut problem…i am kind of lost here