-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.tsx
64 lines (47 loc) · 1.37 KB
/
index.tsx
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
import { useState, useEffect, useMemo, useCallback } from "react";
import fetchCep from "cep-promise";
export type Cep = {
cep: string;
state: string;
city: string;
street: string;
neighborhood: string;
};
export type ErrorCep = { hasError: boolean, message: string };
export type HookReturn = [boolean, Cep, ErrorCep];
const INITIAL_CEP: Cep = {
cep: "",
state: "",
city: "",
street: "",
neighborhood: ""
};
const useCep = (search: string | number): HookReturn => {
const cleanCep: string = useMemo(() => String(search).replace(/\D+/g, ""), [
search
]);
const [loading, setLoading] = useState<boolean>(false);
const [cep, setCep] = useState<Cep>(INITIAL_CEP);
const [error, setError] = useState<ErrorCep>({ hasError: false, message: "" });
const searchCep = useCallback(async () => {
setLoading(true);
setError({ hasError: false, message: "" });
try {
const response = await fetchCep(cleanCep);
setCep(response);
setLoading(false);
} catch (error) {
const message: string = error instanceof Object ? String(error) : error;
setCep(INITIAL_CEP);
setError({ hasError: true, message });
setLoading(false);
}
}, [cleanCep]);
useEffect(() => {
if (cleanCep.length === 8) {
searchCep();
}
}, [cleanCep, searchCep]);
return [loading, cep, error];
};
export default useCep;