forked from adamhaile/surplus-realworld
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestErrors.tsx
More file actions
35 lines (31 loc) · 1.07 KB
/
RequestErrors.tsx
File metadata and controls
35 lines (31 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import S from 's-js';
import * as Surplus from 'surplus';
import { RequestErrors as RequestErrorsT } from '../app/client';
/**
* Re-usable component that watches a request for UNPROCESSABLE (422) responses
* indicating validation or business-logic failures in the request, and displays
* the provided error messages.
*
* @param request - a signal bearing the request to watch, or null
*/
export const RequestErrors = ({ request } : { request : () => null | Promise<any> }) => {
const errors = S.value(null as RequestErrorsT | null);
S.on(request, () => {
errors(null);
if (request()) request()!.catch(e => {
if (e instanceof Response && e.status === 422) {
e.json().then(errors);
}
throw e;
});
});
return (
<ul class="error-messages" hidden={!errors()}>
{errors() && Object.keys(errors()!.errors).map(field =>
errors()!.errors[field].map(error =>
<li>{field} {error}</li>
)
)}
</ul>
);
}