auth.context.tsx 1.13 KB
Newer Older
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
import React, {
  createContext,
  FC,
  ReactNode,
  useContext,
  useState,
} from "react";
import { IUser } from "../types";
import { getLocalUser, handleLogin, handleLogout } from "./auth.helper";

interface IAuthContext {
  login: (email: string, password: string, cb?: VoidFunction) => Promise<void>;
  logout: (cb?: VoidFunction) => Promise<void>;
  user: IUser;
}

const AuthContext = createContext<IAuthContext>({
  login: async () => {},
  logout: async () => {},
  user: { isLoggedIn: false },
});

export const AuthProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState(getLocalUser());

  const login = async (
    email: string,
    password: string,
    cb: VoidFunction = () => {}
  ) => {
    const user = await handleLogin(email, password);
    setUser(user);
    cb();
  };

  const logout = async (cb: VoidFunction = () => {}) => {
    await handleLogout();
    setUser({ ...user, isLoggedIn: false });
    cb();
  };

  return (
    <AuthContext.Provider value={{ login, logout, user }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);