-
Notifications
You must be signed in to change notification settings - Fork 0
/
authContext.tsx
102 lines (82 loc) · 2.2 KB
/
authContext.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { createContext, ReactNode, useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AxiosResponse } from 'axios';
import { api } from '../services/api';
export type User = {
id: number,
name: string,
email: string,
created_at: string,
updated_at: string
}
type AuthProviderProps = {
children: ReactNode;
}
type UserContextProps = {
user: User;
setUser: (user: User) => void
token: string;
setToken: (token: string) => void
handleSignIn: ({ email, password }: SignInProps) => Promise<SignInResponseProps>
handleSignUp: ({ name, email, password }: SignUpProps) => Promise<SignUpResponseProps>
handleSignOut: () => void
}
type SignInProps = {
email: string;
password: string;
}
type SignInResponseProps = {
user: User;
token: string;
}
type SignUpProps = {
name: string;
email: string;
password: string;
}
type SignUpResponseProps = {
name: string
email: string
id: string
created_at: string
updated_at: string
}
export const AuthContext = createContext({} as UserContextProps);
export function UserContextProvider({ children }: AuthProviderProps) {
const [user, setUser] = useState<User>({} as User);
const [token, setToken] = useState('');
useEffect(() => {
async function verifySignIn() {
const authData = await AsyncStorage.getItem('AUTH_DATA');
if (authData) {
setUser(JSON.parse(authData).user);
setToken(JSON.parse(authData).token);
}
}
verifySignIn();
}, []);
async function handleSignIn({ email, password }: SignInProps): Promise<SignInResponseProps> {
const signInResponse: AxiosResponse = await api.post('/sessions/login', {
email,
password
});
return signInResponse.data;
}
async function handleSignUp({ name, email, password }: SignUpProps): Promise<SignUpResponseProps> {
const signUpResponse: AxiosResponse = await api.post('/users', {
name,
email,
password
});
return signUpResponse.data;
}
async function handleSignOut() {
await AsyncStorage.removeItem('AUTH_DATA');
setUser({} as User);
}
return (
<AuthContext.Provider value={{ user, setUser, token, setToken, handleSignIn, handleSignUp, handleSignOut }}>
{children}
</AuthContext.Provider>
);
}