context.js 2.59 KB
Newer Older
1
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
Kim, Subin's avatar
context    
Kim, Subin committed
2
import { useHistory, useLocation } from "react-router-dom";
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import authApi from "../apis/auth.api";
import catchErrors from './catchErrors';

const AuthContext = createContext({
  error: "",
  user: { id: "", role: "user", name: "" },
  setUser: () => { },
  login: () => Promise.resolve(false),
  logout: () => { },
  catchErrorAuth: (error, displayError) => { },
});

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState({ id: "", role: "user", name: "" });
Kim, Subin's avatar
context    
Kim, Subin committed
17
18
19
  const [error, setError] = useState("");
  const history = useHistory()
  const { pathname } = useLocation()
20
  const getUser = async () => {
Kim, Subin's avatar
context    
Kim, Subin committed
21
22
23
24
25
26
27
28
    try {
      const resUser = await authApi.getUser();
      setUser({ ...user, ...resUser });
      // console.log("context use")
      // if (pathname === "/admin" && user.role !== "admin") history.push('/home')
    } catch (error) {
      catchErrorAuth(error, setError);
    }
29
  }
Kim, Subin's avatar
context    
Kim, Subin committed
30

31
32
33
34
35
36
37
38
  useEffect(() => {
    getUser();
  }, []);

  const login = useCallback(async (data) => {
    try {
      setError("");
      const user = await authApi.login(data);
39
      localStorage.setItem("login", true)
40
41
42
43
44
45
46
47
48
49
50
51
52
      setUser(user);
      console.log('setUser 결과', user)
      return true;
    } catch (error) {
      catchErrors(error, setError);
      return false;
    }
  }, []);

  const logout = useCallback(async () => {
    try {
      setError("");
      const user = await authApi.logout();
53
      localStorage.removeItem("login")
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
      setUser(user);
      alert("로그아웃 되었습니다.");
    } catch (error) {
      catchErrors(error, setError);
    }
  }, []);

  const catchErrorAuth = useCallback(async (error, displayError) => {
    let errMsg;
    if (error.response) {
      if (typeof error.response.data === "string") {
        errMsg = error.response.data;
        console.log('Error response:', errMsg);
      } else {
        const { data } = error.response;
        if (data.redirectUrl) {
          errMsg = data.message;
          console.log('Error response with redirected message:', errMsg);
          return await logout();
        }
      }
    } else if (error.request) {
      errMsg = error.request;
      console.log('Error request:', errMsg);
    } else {
      errMsg = error.message;
      console.log("Error message:", errMsg)
    }
    displayError(errMsg);
  }, []);

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

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

Kim, Subin's avatar
context    
Kim, Subin committed
94
export { AuthProvider, useAuth };