-
Notifications
You must be signed in to change notification settings - Fork 0
/
citizenContext.tsx
78 lines (61 loc) · 1.78 KB
/
citizenContext.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React, { createContext, ReactNode } from 'react';
import { useAuth } from '../hooks/useAuth';
import { AxiosResponse } from 'axios';
import { api } from '../services/api';
type CitizenProps = {
name: string;
cpf: string;
birthDate: string;
vaccineName: string;
vaccineDose: string;
}
export interface CitizenResponseProps extends CitizenProps {
id: string;
created_at: string;
updated_at: string;
}
type CitizenProviderProps = {
children: ReactNode;
}
type CitizenContextProps = {
getCitizens: () => Promise<CitizenResponseProps[]>;
registerCitizen: ({ name, cpf, birthDate, vaccineName, vaccineDose }: CitizenProps) => Promise<CitizenResponseProps>;
}
export const CitizenContext = createContext({} as CitizenContextProps);
export function CitizenContextProvider({ children }: CitizenProviderProps) {
const auth = useAuth();
async function getCitizens(): Promise<CitizenResponseProps[]> {
const citizenResponse: AxiosResponse = await api.get('/citizens', {
headers: {
Authorization: `Bearer ${auth.token}`
}
});
return citizenResponse.data;
}
async function registerCitizen({ name, cpf, birthDate, vaccineName, vaccineDose }: CitizenProps): Promise<CitizenResponseProps> {
cpf = cpf.replace(/[^\d]/g, '');
birthDate = new Date(
parseInt(birthDate.substring(6, 10)),
parseInt(birthDate.substring(3, 5)) - 1,
parseInt(birthDate.substring(0, 2)),
).toString();
const data = {
name,
cpf,
birthDate,
vaccineName,
vaccineDose
};
const citizenResponse: AxiosResponse = await api.post('/citizens', data, {
headers: {
Authorization: `Bearer ${auth.token}`
}
});
return citizenResponse.data;
}
return (
<CitizenContext.Provider value={{ getCitizens, registerCitizen }}>
{children}
</CitizenContext.Provider>
);
}