forked from api-platform/admin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseOnSubmit.ts
More file actions
143 lines (136 loc) · 4.03 KB
/
useOnSubmit.ts
File metadata and controls
143 lines (136 loc) · 4.03 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import { useCallback } from 'react';
import { useCreate, useNotify, useRedirect, useUpdate } from 'react-admin';
import type { HttpError, RaRecord } from 'react-admin';
import { useParams } from 'react-router-dom';
import lodashIsPlainObject from 'lodash.isplainobject';
import getIdentifierValue from './getIdentifierValue.js';
import type { SubmissionErrors, UseOnSubmitProps } from './types.js';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const findFile = (values: any[]): Blob | undefined =>
values.find((value) =>
Array.isArray(value)
? findFile(value)
: lodashIsPlainObject(value) &&
Object.values(value).find((val) => val instanceof File),
);
const useOnSubmit = ({
resource,
schemaAnalyzer,
fields,
mutationOptions,
mutationMode = 'pessimistic',
transform,
redirectTo = 'list',
}: UseOnSubmitProps): ((
values: Partial<RaRecord>,
) => Promise<SubmissionErrors | undefined>) => {
const { id: routeId } = useParams<'id'>();
const id = decodeURIComponent(routeId ?? '');
const [create] = useCreate();
const [update] = useUpdate();
const notify = useNotify();
const redirect = useRedirect();
return useCallback(
async (values: Partial<RaRecord>) => {
const isCreate = id === '';
const data = transform ? transform(values) : values;
// Identifiers need to be formatted in case they have not been modified in the form.
if (!isCreate) {
Object.entries(values).forEach(([key, value]) => {
const identifierValue = getIdentifierValue(
schemaAnalyzer,
resource,
fields,
key,
value,
);
if (identifierValue !== value) {
data[key] = identifierValue;
}
});
}
try {
const response = await (isCreate ? create : update)(
resource,
{
...(isCreate ? {} : { id }),
data,
meta: { hasFileField: !!findFile(Object.values(values)) },
},
{ returnPromise: true },
);
const success =
mutationOptions?.onSuccess ??
((record: RaRecord) => {
notify(
isCreate ? 'ra.notification.created' : 'ra.notification.updated',
{
type: 'info',
messageArgs: { smart_count: 1 },
},
);
redirect(redirectTo, resource, record.id, record);
});
success(
response,
{
data: response,
...(isCreate ? {} : { id, previousData: values }),
},
{},
);
return undefined;
} catch (mutateError) {
const submissionErrors = schemaAnalyzer.getSubmissionErrors(
mutateError as HttpError,
);
const failure =
mutationOptions?.onError ??
((error: string | Error) => {
// Notification will be handled by the useNotifyIsFormInvalid hook.
if (submissionErrors && mutationMode === 'pessimistic') {
return;
}
const message =
typeof error === 'string'
? error
: error.message || 'ra.notification.http_error';
let errorMessage;
if (typeof error === 'string') {
errorMessage = error;
} else if (error?.message) {
errorMessage = error.message;
}
notify(message, {
type: 'warning',
messageArgs: { _: errorMessage },
});
});
failure(
mutateError as Error,
{
data: values,
...(isCreate ? {} : { id, previousData: values }),
},
{},
);
return submissionErrors ?? {};
}
},
[
fields,
id,
mutationMode,
mutationOptions,
notify,
redirect,
redirectTo,
resource,
schemaAnalyzer,
transform,
create,
update,
],
);
};
export default useOnSubmit;