context.js 2.37 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
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom';
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 [error, setError] = useState("");
  const [user, setUser] = useState({ id: "", role: "user", name: "" });
  const getUser = async () => {
    const { id, role, userName } = await authApi.getUser();
    const user = { id: id, role: role, name: userName };
    setUser(user);
  }
  useEffect(() => {
    getUser();
  }, []);

  const login = useCallback(async (data) => {
    try {
      setError("");
      const user = await authApi.login(data);
31
      localStorage.setItem("login", true)
32
33
34
35
36
37
38
39
40
41
42
43
44
      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();
45
      localStorage.removeItem("login")
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
      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);

export { AuthProvider, useAuth };