Merge pull request #7821 from mabashian/7814-form-error

Handle form submission errors that may be deeply nested in the return object

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot] 2020-08-06 16:09:29 +00:00 committed by GitHub
commit 16ce7b4647
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 8 deletions

View File

@ -2,6 +2,26 @@ import React, { useState, useEffect } from 'react';
import { useFormikContext } from 'formik';
import { Alert } from '@patternfly/react-core';
const findErrorStrings = (obj, messages = []) => {
if (typeof obj === 'string') {
messages.push(obj);
} else if (typeof obj === 'object') {
Object.keys(obj).forEach(key => {
const value = obj[key];
if (typeof value === 'string') {
messages.push(value);
} else if (Array.isArray(value)) {
value.forEach(arrValue => {
messages = findErrorStrings(arrValue, messages);
});
} else if (typeof value === 'object') {
messages = findErrorStrings(value, messages);
}
});
}
return messages;
};
function FormSubmitError({ error }) {
const [errorMessage, setErrorMessage] = useState(null);
const { setErrors } = useFormikContext();
@ -18,14 +38,7 @@ function FormSubmitError({ error }) {
const errorMessages = error.response.data;
setErrors(errorMessages);
let messages = [];
Object.values(error.response.data).forEach(value => {
if (Array.isArray(value)) {
messages = messages.concat(value);
} else {
messages.push(value);
}
});
const messages = findErrorStrings(error.response.data);
setErrorMessage(messages.length > 0 ? messages : null);
} else {
/* eslint-disable-next-line no-console */

View File

@ -52,4 +52,30 @@ describe('<FormSubmitError>', () => {
expect(global.console.error).toHaveBeenCalledWith(error);
global.console = realConsole;
});
test('should display error message if field error is nested', async () => {
const error = {
response: {
data: {
name: 'There was an error with name',
inputs: {
url: 'Error with url',
},
},
},
};
let wrapper;
await act(async () => {
wrapper = mountWithContexts(
<Formik>{() => <FormSubmitError error={error} />}</Formik>
);
});
wrapper.update();
expect(
wrapper.find('Alert').contains(<div>There was an error with name</div>)
).toEqual(true);
expect(wrapper.find('Alert').contains(<div>Error with url</div>)).toEqual(
true
);
});
});