forked from kriasoft/react-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseErrors.ts
More file actions
57 lines (49 loc) · 1.36 KB
/
Copy pathuseErrors.ts
File metadata and controls
57 lines (49 loc) · 1.36 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
/* SPDX-FileCopyrightText: 2014-present Kriasoft <hello@kriasoft.com> */
/* SPDX-License-Identifier: MIT */
import * as React from "react";
import { PayloadError } from "relay-runtime";
declare module "relay-runtime" {
interface PayloadError {
errors?: {
[key: string]: string[];
};
}
}
type Input = {
[key: string]: string | number | null;
};
type Errors<T extends Input> = {
[key in keyof T | "_"]?: string[];
};
const empty: Errors<Input> = {};
/**
* Returns an object containing validation errors and a function to update it.
*
* @example
* const [errors, setErrors] = useErrors();
* const [updateUser] = useMutation<UserMutation>(updateUserMutation);
*
* updateUser({
* variables: { input: ..., dryRun: true },
* onCompleted({ updateUser: data }, errors) {
* setErrors(errors?.[0]);
* }
* })
*/
export function useErrors<T extends Input>(): [
Errors<T>,
(payloadError?: PayloadError | ((prev: Errors<T>) => Errors<T>)) => void
] {
const [errors, set] = React.useState<Errors<T>>(empty);
const setErrors = React.useCallback(
function setErrors(err?: PayloadError | ((prev: Errors<T>) => Errors<T>)) {
if (typeof err === "function") {
set(err);
} else {
set(err?.errors || (err && { _: [err.message] }) || empty);
}
},
[set]
);
return [errors, setErrors];
}